【发布时间】:2017-08-25 13:42:50
【问题描述】:
在 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));
}
}
此方法还可用于设置默认字符串长度/空值等。
我查看了 EF Core 模型和关联类型,但找不到以迁移构建器制定的方式应用等效约定的方法,或者不会导致迁移构建器完全拒绝模型。这完全令人沮丧,而且似乎是倒退的。
更新
将以下内容添加到 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.
【问题讨论】:
-
@IvanStoev 试过这个 - 对呈现的迁移没有影响。
-
在我的测试中,迁移生成器会考虑它。目前(即使在2.0)AFAIK也没有其他方法。但是,如果您/有人找到一些东西会很有趣。祝你好运。
标签: c# entity-framework asp.net-core entity-framework-core