EF Core 5如何停止ValueGeneratedOnAdd被添加到我所有的模型



我正在从EF Core 2.2迁移到5,并为我的id使用显式的Guids,即不生成

将非跟踪子值添加到实体时会导致错误

裁判:https://github.com/dotnet/efcore/issues/17747

是否有办法可以配置整个model tonotValueGeneratedOnAdd()添加到我的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类型的PKs是按约定的,而且EF Core目前(v5.x)也没有提供修改约定的方法,您可以使用元数据API来做您需要的事情。

OnModelCreatingoverride的末尾添加以下代码片段(以确保已经发现了所有实体类型):

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;
}

最新更新