[英]ASP.NET Core 3.0 MVC update model with list objects - add object
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.
我可以编辑这个 model。 Controller: ...
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: ...但问题是当我想在列表中添加一个项目时: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.编辑“发票”记录时,可以编辑该记录的所有元素以及附加到它的“Invoice_item”列表的元素。 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 your item
,change your code like below.您只需要在您的
item
中添加一个Invoice_itemID
,更改您的代码,如下所示。
Invoice_item item = new Invoice_item()
{
//add this line.
Invoice_itemID = new Guid(),
Description = "Description 2",
Price = 2,
qty = 2
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.