如何在不指定关系的情况下播种数据



我有如下实体:

public class EntityA
{
public int Id { get; init; }
public bool Enabled { get; set; } = true;
public string Name { get; set; }
public string Description { get; set; }
public int SomeEntityId { get; set; }
public SomeEntity SomeEntity { get; set; }
}

和SomeEntity:

public class SomeEntity
{
public int Id { get; init; }
public string Name { get; set; }
public ICollection<EntityA> EntitiesA { get; set; }
}

我想要种子EntityA没有任何关系:

public void Configure(EntityTypeBuilder<EntityA> builder)
{
builder.HasData(new EntityA
{
Id = 1,
Enabled = true,
Name = "...",
Description = "..."
});
}

但是我总是得到错误当update-database:

INSERT语句与外键约束"fk_entitiesa_someentities_someentityid"冲突。冲突发生在数据库"databasname"、表"dbo. someentities"和列"Id"中。语句已被终止。

我知道它发生是因为EF希望我的SomeEntity不为空,但我不能使它为空,因为这个种子数据确实是唯一的(它只是没有外键的数据)。

我怎样才能绕过这个?

也许你应该让你的外键属性为空,即,而不是public int SomeEntityIdpublic int? SomeEnttiyId

public class EntityA
{
public int Id { get; init; }
public bool Enabled { get; set; } = true;
public string Name { get; set; }
public string Description { get; set; }
public int? SomeEntityId { get; set; }
public SomeEntity SomeEntity { get; set; }
}

这样就可以在数据库中插入一条外键SomeEntityId为空值的EntityA记录。

最新更新