我正在从EF Core 2.2迁移到5,并为我的ID使用显式的Guid,即未生成
将非跟踪的子值添加到实体时,这会导致错误
参考:https : //github.com/dotnet/efcore/issues/17747
有没有一种方法可以将整个模型配置为不添加ValueGeneratedOnAdd()
到我的id列中,而无需在每个模型上都明确设置呢?
public class ParentData
{
public Guid Id { get; set; }
public IList<ChildData> Children { get; set; } = new List<ChildData>();
}
public class ChildData
{
public Guid Id { get; set; }
public Guid ParentId { get; set; }
public ParentData Parent { get; set; }
}
谢谢
由于ValudGeneratedOnAdd
对Guid
类型的PK是按照惯例,也是EF核心目前(V5.x中)不提供修改公约的方式,你可以使用元数据API来完成你所需要的。
添加以下代码段末的OnModelCreating
覆盖(以确保所有的实体类型已发现的):
foreach (var property in modelBuilder.Model
.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ValueGenerated == ValueGenerated.OnAdd
&& p.IsPrimaryKey()
&& p.ClrType == typeof(Guid)))
{
property.ValueGenerated = ValueGenerated.Never;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句