
[英]How do I setup a one-to-one-or-zero relationship with Entity Framework AND expose the foreign key on the child entity?
[英]Entity Framework Core Insert list of one-to-one-or-zero (shared primary key association) foreign key conflict
我正在尝试插入一个对象列表。 这些对象由 2 个独立的子对象组成,通过 0 到 1 的关系链接。
如果我一次插入一个 object,它会起作用,但如果我尝试插入多个,对SaveChanges
的调用会引发“外键”错误。 我知道 0 对 1 关系需要知道主要关系 object 索引。 但是,有没有办法解决这个问题?
这就是我想要做的:
此代码有效:
ElementoVariante ElementoVariante1 = new()
{
TipoElementoNome = EnumTipoElemento.ProdottoFinito,
ElementoPadreId = 17491,
SchedaSerieProdotto = new SchedaSerieProdotto()
{
S = s,
P = p
}
};
context.ElementoVariante.Add(ElementoVariante1);
context.SaveChanges();
但是此代码不起作用:
ElementoVariante ElementoVariante1 = new()
{
TipoElementoNome = EnumTipoElemento.ProdottoFinito,
ElementoPadreId = 17491,
SchedaSerieProdotto = new SchedaSerieProdotto()
{
S = s,
P = p
}
};
context.ElementoVariante.Add(ElementoVariante1);
ElementoVariante ElementoVariante2 = new()
{
TipoElementoNome = EnumTipoElemento.ProdottoFinito,
ElementoPadreId = 17491,
SchedaSerieProdotto = new SchedaSerieProdotto()
{
S = s,
P = p
}
};
context.ElementoVariante.Add(ElementoVariante2);
context.SaveChanges();
我得到了它。 我认为问题出在 EF Core 5 内部。表“SchedaSerieProdotto”有一个父表“SchedaBase”,我这样做:“builder.Entity().ToTable("SchedaSerieProdotto")”拆分表。 我删除了它,将 2 个表合并为一个,添加了 Discriminator 列,现在一切正常。 我认为这是 EF Core 5 的 TPT 问题,也许他们在最新版本中修复了它,比如 EF Core 7
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.