Capitalizing the first letter of the property name in Entity Framework

.net c# entity-framework sql

Question

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:

CamelCase (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?

1
18
5/6/2013 6:52:59 PM

Popular Answer

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".

15
11/5/2013 3:01:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow