我有一堂课
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_Id
和Receipts
表中的Invoices
保持为NULL。但是,如果我这样链接它们:
client.Invoices.Add(invoice1);
client.Receipts.Add(receipt1);
client.Receipts.Add(receipt2);
context.SaveChanges();
然后正确更新数据库中的Client_Id
。为什么会这样?