1

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

当在上下文中调用 savechages 时,我收到此错误。“'EchoEntities.LetterRecipients' 中的实体参与了 'FK_LetterRecipient_Letter' 关系。找到了 0 个相关的 'Letter'。预计有 1 个 'Letter'。”

此外,当仅添加 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();
}
4

1 回答 1

1

我只是在 EF v1 中做类似的事情,我认为你需要移动调用:

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

初始化letter对象后。您还需要 context.SaveChanges();在最后打电话。

于 2011-07-08T10:20:59.663 回答