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

后端 未结 1 575
离开以前
离开以前 2021-01-14 07:20

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 cod

1条回答
  •  礼貌的吻别
    2021-01-14 08:12

    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
    {
        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();
    
        // 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().Add(p);
        db.SaveChanges();
    }
    
    using (var db = new MyContext())
    {
        var x = db.Set().ToList();
    }
    

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

    0 讨论(0)
提交回复
热议问题