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.
你就不能使用的變化[遍歷所有的EF模型的所有屬性/反映設置列類型(https://stackoverflow.com/questions/41468722/loop-reflect-through-所有的屬性納入所有-EF-模型到組列型/ 41469383#41469383)? –
@IvanStoev嘗試過 - 對渲染的遷移沒有影響。 – Matt
在我的測試中,它被遷移發生器考慮。目前還沒有其他方式(即使在2.0)AFAIK。但如果你/某人發現了某些東西,這將會很有趣。祝你好運。 –