I have the following classes:
public class Invoice
{
[key]
public Guid InvoiceID { get; set; }
public string Name { get; set; }
public List<Invoice_item> Invoice_items { get; set; }
public Invoice()
{
InvoiceID = Guid.NewGuid();
Invoice_items = new List<Invoice_item>();
}
}
and:
public class Invoice_item
{
[Key]
public Guid Invoice_itemID { get; set; }
public string Description{ get; set; }
public int Price { get; set; }
public int qty { get; set; }
public Invoice_item()
{
Invoice_itemID = Guid.NewGuid();
}
}
It works fine. I can edit this model. Controller: ...
Invoice invoice = await _context.Invoice.Include(i => i.Invoice_items).Where(x => x.InvoiceID == id).FirstOrDefaultAsync();
invoice.Name = "2020/122";
invoice.Invoice_items[0].Description = "Some name";
invoice.Invoice_items[0].Price = 1;
invoice.Invoice_items[0].qty = 1;
_context.Update(invoice);
await _context.SaveChangesAsync();
// WORK OK
But the problem is when I want to add an item to the list: Controller: ...
Invoice invoice = await _context.Invoice.Include(i => i.Invoice_items).Where(x => x.InvoiceID == id).FirstOrDefaultAsync();
invoice.Name = "2020/122";
invoice.Invoice_items[0].Description = "Description 1";
invoice.Invoice_items[0].Price = 1;
invoice.Invoice_items[0].qty 1;
Invoice_item item = new Invoice_item()
{
Description = "Description 2",
Price = 2,
qty = 2
};
invoice.Invoice_items.Add(item); // PROBLEM
_context.Update(invoice);
await _context.SaveChangesAsync();
When editing the "Invoice" record, it is possible to edit all elements of the record and the elements of the "Invoice_item" list attached to it. The problem occurs when I want to add an item to the "Invoice_item" list attached to the "Invoice" record.
Please help.
You just need to add a
Invoice_itemID
in youritem
,change your code like below.