使用Entity Framework更改模型创建时的列名称

时间:2018-03-05 22:34:04

标签: c# entity-framework propertyinfo

我正在寻找使用Entity Framework构建数据库期间更改列名的任何解决方案。

我有以下示例代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<SysUser>().Property(p => p.Enable).HasColumnName("newColumnName");
}

这有效,但我希望自动执行更改列名的操作,即获取实体的某些部分,并更改列名。

为此,我写了下面的代码,但是我被困了。为了获取所有实体,我使用了Types,但无法将其转换为EntityTypeConfiguration<>

// This gets all of defined DbSet<> in database contexts
var contextProp = this.GetType().GetProperties().Where(p => (p.PropertyType.GetGenericArguments().Count() == 1)).ToList();

foreach (PropertyInfo entity in contextProp )
{
   // get generic type from DbSet
   Type entityType = entity.PropertyType.GetGenericArguments()[0];
   foreach (PropertyInfo entityProp in entityType.GetProperties())
   {
      // I'm stuck here
      // entityType = SysUser
      // entityProp = Enable
   }
}

为什么我这样做?在一堂课中我有另一堂课。 实体框架呈现字段,在列名末尾添加方法名称。

例如:

public class x
{
   public int Value { get; set; }
}

public class y
{
   public x { get; set; }
}

// ... some database context
DbSet<y> y { get; set; }

使用名为y的表创建数据库,其中包含名为x_Value的列。

我无法使用ColumnAttribute,因为此选项为所有类设置相同的列名。列的名称应与属性x { get; set; }相同。

0 个答案:

没有答案