Entity framework core EF Core 5如何停止将值生成和添加到我的所有模型
我正在从EF Core 2.2迁移到5,并为我的ID使用显式GUID,即未生成 向实体添加未跟踪的子值时,这会导致错误 参考: 是否有一种方法可以将整体模型配置为非将Entity framework core EF Core 5如何停止将值生成和添加到我的所有模型,entity-framework-core,Entity Framework Core,我正在从EF Core 2.2迁移到5,并为我的ID使用显式GUID,即未生成 向实体添加未跟踪的子值时,这会导致错误 参考: 是否有一种方法可以将整体模型配置为非将ValueGeneratedOnAdd()添加到我的id列,而无需在每个列上明确设置它 public class ParentData { public Guid Id { get; set; } public IList<ChildData> Children { get
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; }
}
公共类ParentData
{
公共Guid Id{get;set;}
公共IList子项{get;set;}=new List();
}
公共类儿童数据
{
公共Guid Id{get;set;}
公共Guid ParentId{get;set;}
公共ParentData父项{get;set;}
}
谢谢由于
Guid
的valuedGeneratedOnAdd
类型PKs是,而且EF Core当前(v5.x)不提供修改约定的方法,因此您可以使用元数据API来执行您需要的操作
在ModelCreatingoverride的末尾添加以下代码段(以确保已发现所有实体类型):
谢谢Ivan,我最后还添加了p.Name==“Id”,这适用于我们的约定
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;
}