在我的应用程序中,我有很多模型,但与我的问题相关的是:
public class MarketSale
{
public int ID { get; set; }
public DateTime SaleDate { get; set; }
public virtual List<DiscountedItem> Discounts { get; set; }
public virtual List<Item> ItemsSold { get; set; }
public decimal SalesTotal { get; set; }
}
如您所见,有一个DiscountedItem对象列表,它们在创建MarketSale对象的同时创建,并且不存在于与任何其他对象相关的任何其他上下文中。 Item类型的对象列表是对数据库中已有的现有项的引用,只是在创建MarketSale项时添加为引用。我能够创建MarketSale项并在列表中正确添加DiscountedItem对象,并添加对已存在的Item对象的引用,而无需在表中添加新条目。但是,当我编辑MarketSale对象时,我能够添加新的DiscountedItem对象,但无法添加对其他项的引用。当我尝试在ItemsSold列表中添加另一个引用后转到详细信息视图时,它仅显示最初创建MarketSale实例时添加的项目。 (Item是以下类的父类:Earring,Headband,Hairclip,Hairpin)
这是我的控制器编辑方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,SaleDate,SalesTotal,Discounts,ItemsSold"] MarketSale marketSale)
{
if (ModelState.IsValid)
{
List<Item> myItems = new List<Item>();
for (int i=0; i < marketSale.ItemsSold.Count; i++)
{
List<Earring> earrings = db.Earrings.ToList();
List<Hairclip> hairclips = db.Hairclips.ToList();
List<Hairpin> hairpins = db.Hairpins.ToList();
List<Headband> headbands = db.Headbands.ToList();
Item item = null;
item = earrings.Find(c => (c.InventoryNum == marketSale.ItemsSold[i].InventoryNum));
if (item == null)
{
item = hairclips.Find(c => (c.InventoryNum == marketSale.ItemsSold[i].InventoryNum));
}
if (item == null)
{
item = hairpins.Find(c => (c.InventoryNum == marketSale.ItemsSold[i].InventoryNum));
}
if (item == null)
{
item = headbands.Find(c => (c.InventoryNum == marketSale.ItemsSold[i].InventoryNum));
}
marketSale.ItemsSold[i] = item;
item = null;
}
List<DiscountedItem> myDiscounts = new List<DiscountedItem>();
foreach(DiscountedItem disc in marketSale.Discounts)
{
List<DiscountedItem> discounts = db.DiscountedItems.ToList();
DiscountedItem i = null;
i = discounts.Find(c => (c.Id == disc.Id));
if(i != null)
{
if (i.DiscountAmount != disc.DiscountAmount)
{
i.DiscountAmount = disc.DiscountAmount;
db.Entry(i).State = EntityState.Modified;
}
myDiscounts.Add(i);
}
else
{
myDiscounts.Add(disc);
db.DiscountedItems.Add(disc);
}
}
marketSale.Discounts = myDiscounts;
db.Entry(marketSale).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(marketSale);
}
如果有人知道为什么这不能正常工作或者我如何改进我的代码或我正在制作的任何其他错误的任何建议,我会很高兴听到他们。谢谢!