首先违反主键代码的实体框架

时间:2018-04-25 22:06:09

标签: c# ef-code-first

这是Invoices类:

public class Invoices
{
    public Guid Id { get; set; }
    public Customers Customer { get; set; }
    public List<Payments> Payments { get; set; }
    public Double Total { get; set; }
    public DateTime Date { get; set; }
    public Boolean Payed { get; set; }
}

这是Payments类:

public class Payments
{
    public Guid Id { get; set; }
    public Products Product { get; set; }
    public Int32 Quantity { get; set; } 
}

当我尝试添加发票时

Invoices addInvoice = new Invoices(customer, payments, total, date, payed);
Context.Invoices.Add(addInvoice);
Context.SaveChanges();

我收到此消息:

Violation products

但我并没有尝试添加产品。这是因为我有一个Payments列表,其中包含每笔付款的产品?我该如何解决这个问题?

感谢所有回答此问题的人。

更新:我发现为什么EF尝试再次添加产品。

我改变了这一行

pagamenti.Add(new Payments(new Products(idProduct, nameOfProduct, price)));

到此:

Products product = Context.Products.Where((p) => p.Id == idProdotto).First();
pagamenti.Add(new Payments(product, quantita));

现在它正常运作

0 个答案:

没有答案