在EF6中,可以在模型构建期间基于属性类型定义约定,如此......
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));
}
}
此方法也可用于设置默认字符串长度/ null-ness,等等。
我查看了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();
}
...在Add-Migration
上生成以下消息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 :(得分: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()");
}