实体框架 - 无法使用 savechanges 添加具有新子级的新实体

发布于 2024-08-05 15:08:44 字数 918 浏览 6 评论 0原文

我正在创建一个名为“信件”的对象,其中添加了多个“收件人”。

当在上下文中调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你与清晨阳光 2024-08-12 15:08:44

我刚刚在 EF v1 中做了类似的事情,我认为您需要移动调用:

context.AddToLetters(letter);
context.SaveChanges();

在初始化 letter 对象之后。您还需要在最后调用 context.SaveChanges();

I was just doing a similar thing in EF v1 and I think you need to move the calls:

context.AddToLetters(letter);
context.SaveChanges();

after you intialize the letter object. You also need to call context.SaveChanges(); at the very end.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文