EF Code First Fluent API - lowercase first letters of all columns

旧城冷巷雨未停 提交于 2019-12-19 09:53:17

问题


I'm hoping to set up an EF Code First convention where all of the column names of the properties have a lowercase first letter.

However, I have other fluent API code that changes column names from the default. I can't seem to find a way to get access to the current column name of a property in order to lowercase the first letter. Starting with the PropertyInfo, as in modelBuilder.Properties() is not enough because the column name may have already been set to be different than the member name.

How do I generically tell EF Code First to lowercase the first letter of all column names?


回答1:


OK, the DBA's are speaking. Let's bow our heads in reverence and see what we can do. I'm afraid that in EF 5 (and lower) there's not much you can do to make it easy. In EF 6 there is this feature of Custom Code First Conventions which actually make it a piece of cake. I just tried a small sample:

// Just some POCO
class Person
{
  public int PersonId { get; set; }
  public string PersonName { get; set; }
}

// A custom convention.
class FirstCharLowerCaseConvention : IStoreModelConvention<EdmProperty>
{
    public void Apply(EdmProperty property, DbModel model)
    {
        property.Name = property.Name.Substring(0, 1).ToLower()
                      + property.Name.Substring(1);
    }
}

class MyContext : DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Person>();

    // Add the convention to the modelbuilder.
    modelBuilder.Conventions.Add(new FirstCharLowerCaseConvention());

    base.OnModelCreating(modelBuilder);
  }
}

After running

using (var db = new MyContext())
{
  db.Database.Create();
}

my database has a People table with personId and personName.

And some simple CRUD actions work flawlessly:

using (var db = new MyContext())
{
    var p = new Person { PersonName = "Another Geek" };
    db.Set<Person>().Add(p);
    db.SaveChanges();
}

using (var db = new MyContext())
{
    var x = db.Set<Person>().ToList();
}

So if the DBA's want their conventions, you can demand a new toy :)



来源:https://stackoverflow.com/questions/15160212/ef-code-first-fluent-api-lowercase-first-letters-of-all-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!