Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Capitalizing first property name letter

Tags:

In general, I tend to name my sql database columns using the following camel case convention:

camelCase (notice that the first letter is in lower case).

But when working with C#, I like to name my object's public properties in the following convention:

PascalCase (notice the first is in uppwer case).

Entity Framework's default behaviour is to name the created classes' properties to match their relative column names as they are in the database.

Is there any property in the project/solution level which can be changed in order to solve this issue?

like image 322
Mikey S. Avatar asked Jun 28 '11 10:06

Mikey S.


1 Answers

Yes there is. Here you can see the full example:

using System;
using System.Data.Entity;

namespace ConsoleApplication1
{
    class MyDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Properties().Configure(c =>
            {
                var name = c.ClrPropertyInfo.Name;
                var newName = char.ToLower(name[0]) + name.Substring(1);
                c.HasColumnName(newName);
            });
        }

        public MyDbCondenxt(string cs) : base(cs)
        {

        }

        public DbSet<MyModel> MyModels { get; set; }

    }

    class Program
    {
        static void Main(string[] args)
        {
            var context = new MyDbContext ("DefaultConnection");
            context.MyModels.Add(new MyModel{SomeText = "hello"});
            context.SaveChanges();

            Console.ReadLine();
        }
    }

    class MyModel
    {
        public int Id { get; set; }
        public string SomeText { get; set; }
    }


}

The property name is "SomeText" and the column name is "someText".

like image 121
Andrzej Gis Avatar answered Sep 19 '22 14:09

Andrzej Gis