EF Code First Fluent API - 所有列的小写第一个字母 [英] EF Code First Fluent API - lowercase first letters of all columns

查看:285
本文介绍了EF Code First Fluent API - 所有列的小写第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望设置一个EF Code First约定,其中属性的所有列名都有一个小写的第一个字母。

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.

但是,我有其他流畅的API代码,将列名从默认值更改。为了缩小第一个字母,我似乎找不到访问属性的当前列名称的方法。从PropertyInfo开始,与modelBuilder.Properties()一样不够,因为列名可能已经设置为与成员名不同。

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.

我如何一般来说,EF Code First会缩小所有列名的第一个字母?

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

推荐答案

OK,DBA正在说话。让我们尊敬我们,看看我们能做什么。恐怕在EF 5(和更低版本)中,没有多少可以做到这一点。在EF 6中,实际上有自定义代码第一约定的功能它是一块蛋糕我刚刚尝试了一个小样本:

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

运行

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

我的数据库有一个 People 表与 personId personName

my database has a People table with personId and personName.

一些简单的CRUD操作是完美的:

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

所以如果DBA想要他们的约定,你可以要求一个新的玩具:)

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

这篇关于EF Code First Fluent API - 所有列的小写第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆