2017-08-25 129 views
1

在EF6有可能建模过程中定义基于属性类型的约定,像这样......EF核心建模约定

public interface IEntity 
{ 
    Guid Id { get; } 
} 

public class MyEntity : IEntity 
{ 
    public Guid Id { get; set; } 
} 

public class MyDbContext : DbContext 
{ 
    public override void OnModelCreating(DbModelBuilder builder) 
    { 
     builder 
      .Properties<Guid>() 
      .Where(x => x.Name == nameof(IEntity.Id) 
      .Configure(a=>a.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)); 
    } 
} 

这种方法也可以用来设置默认的字符串长度/空值等等,等等。

我已经查看了EF核心模型和关联的类型,可以发现没有办法以迁移构建器制定的方式应用等效约定,或者不会导致迁移构建器完全拒绝该模型。这完全令人沮丧,而且看起来倒退了。

更新

添加以下到OnModelCreating事件......

foreach (var pb in builder.Model 
    .GetEntityTypes() 
    .Where(x=>typeof(IEntity).IsAssignableFrom(x.ClrType)) 
    .SelectMany(t => t.GetProperties()) 
    .Where(p => p.ClrType == typeof(Guid) && p.Name == nameof(IEntity.Id)) 
    .Select(p => builder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name))) 
{ 
    pb.UseSqlServerIdentityColumn(); 
} 

...产生一个附加组件迁移以下消息

Identity value generation cannot be used for the property 'Id' on entity type 'Tenant' because the property type is 'Guid'. Identity value generation can only be used with signed integer properties. 
+0

你就不能使用的变化[遍历所有的EF模型的所有属性/反映设置列类型(https://stackoverflow.com/questions/41468722/loop-reflect-through-所有的属性纳入所有-EF-模型到组列型/ 41469383#41469383)? –

+0

@IvanStoev尝试过 - 对渲染的迁移没有影响。 – Matt

+0

在我的测试中,它被迁移发生器考虑。目前还没有其他方式(即使在2.0)AFAIK。但如果你/某人发现了某些东西,这将会很有趣。祝你好运。 –

回答

0

这做工作,但它很不雅。

foreach (PropertyBuilder pb in builder.Model 
    .GetEntityTypes() 
    .Where(x=>typeof(IEntity).IsAssignableFrom(x.ClrType)) 
    .SelectMany(t => t.GetProperties()) 
    .Where(p => p.ClrType == typeof(Guid) && p.Name == nameof(IEntity.Id)) 
    .Select(p => builder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name))) 
{ 
    pb.ValueGeneratedOnAdd().HasDefaultValueSql("newsequentialid()"); 
}