Capitalizing the first letter of the property name in Entity Framework

.net c# entity-framework sql

Question

I often use the following camel case pattern when naming my sql database columns:

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

However, while using C#, I prefer to give my object's public properties the following names:

CamelCase (notice the first is in uppwer case).

By default, Entity Framework names the attributes of newly formed classes to correspond to the names of the corresponding columns in the database.

Is there a property at the project/solution level that could be altered to address this problem?

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

Popular Answer

That's correct. Here is the whole illustration:

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; }
    }


}

Both the column and the property are named "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