在EF中以一对多关系链接对象时,只有通过集合进行链接才能按预期进行

时间:2019-06-04 15:47:37

标签: .net entity-framework

我有一堂课

  public class Client
    {
        public Guid Id {get; set;}
        public virtual List<Receipt> Receipts { get; set; }
        public virtual List<Invoice> Invoices { get; set; }
    }

然后收据:

   public class Receipt
    {
        public Guid Id { get; set; }
        public string ServiceName {get; set;}
        public decimal Total { get; set; }
        public virtual Client Client { get; set; }
    }

和发票:

[Table("Invoices")]
public class Invoice:Receipt
{
    public double TaxNumber { get; set; }
}

当我有这些类的一些对象时,我尝试以这种方式链接它们:

client = context.Clients.Find(guid1);
receipt1 = context.Receipts.Find(guid2);
receipt2 = context.Receipts.Find(guid3);
invoice1 = context.Invoices.Find(guid4);
//--------------linking
invoice1.Client = client;
receipt1.Client = client;
receipt2.Client = client;
context.SaveChanges();

然后,Client_IdReceipts表中的Invoices保持为NULL。但是,如果我这样链接它们:

client.Invoices.Add(invoice1);
client.Receipts.Add(receipt1);
client.Receipts.Add(receipt2);
context.SaveChanges();

然后正确更新数据库中的Client_Id。为什么会这样?

0 个答案:

没有答案