实体框架 - 无法使用 savechanges 添加具有新子级的新实体
我正在创建一个名为“信件”的对象,其中添加了多个“收件人”。
当在上下文中调用 savechages 时,我收到此错误。 “‘EchoEntities.LetterRecipients’中的实体参与‘FK_LetterRecipient_Letter’关系。找到 0 个相关的‘信件’。预计有 1 个‘信件’。”
此外,当仅添加 1 个收件人时,它可以与两个收件人一起使用,但会失败。
缩短代码:
using(Entites context = new Entities())
{
Letter letter = new Letter
{
ID = Guid.NewGuid(),
details = ""
}
Recipient recip = new Recipient
{
ID = Guid.NewGuid,
Name = "Joe",
Address = "123 some rd",
City = "city",
State = "state",
Zip = "11111"
}
letter.Recipients.Add(recip);
recip = new Recipient
{
ID = Guid.NewGuid,
Name = "Bill",
Address = "123 some rd",
City = "city",
State = "state",
Zip = "11111"
}
letter.Recipients.Add(recip);
context.AddToLetters(letter);
context.SaveChanges();
}
I am creating an object called "letter" which has multiple "recipients" added to it.
When savechages is called on the context i get this error.
"Entities in 'EchoEntities.LetterRecipients' participate in the 'FK_LetterRecipient_Letter' relationship. 0 related 'Letter' were found. 1 'Letter' is expected."
Also when only adding 1 recipient it works with two recipients it fails.
Shortened code:
using(Entites context = new Entities())
{
Letter letter = new Letter
{
ID = Guid.NewGuid(),
details = ""
}
Recipient recip = new Recipient
{
ID = Guid.NewGuid,
Name = "Joe",
Address = "123 some rd",
City = "city",
State = "state",
Zip = "11111"
}
letter.Recipients.Add(recip);
recip = new Recipient
{
ID = Guid.NewGuid,
Name = "Bill",
Address = "123 some rd",
City = "city",
State = "state",
Zip = "11111"
}
letter.Recipients.Add(recip);
context.AddToLetters(letter);
context.SaveChanges();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚在 EF v1 中做了类似的事情,我认为您需要移动调用:
在初始化
letter
对象之后。您还需要在最后调用context.SaveChanges();
。I was just doing a similar thing in EF v1 and I think you need to move the calls:
after you intialize the
letter
object. You also need to callcontext.SaveChanges();
at the very end.