The property 'ID' is part of the object's key information and cannot be modified in asp.net mvc

痞子三分冷 提交于 2019-12-01 09:21:32

You are setting the Product and CookDate once per day, so I assume you want one record per day - which means you mean one object per day. I suspect you actually want something like:

var fd = todaycooked.CookDate; // 2016-07-01
var td = todaycooked.ToCookDate; //2016-11-01

// this doesn't change per day, so only fetch it once
var product = db.Products.Find(todaycooked.ProductID);

for (var date = fd; date <= td; date = date.AddDays(1))
{
    var toAdd = todaycooked.Clone(); // TODO: add a suitable clone method
    toAdd.Product = product;
    toAdd.CookDate = date;
    db.TodayCookeds.Add(toAdd);
    product.Qty = product.Qty + todaycooked.QTY;
    db.SaveChanges();
}

However, you can probably also get away with moving the db.SaveChanges() to outside of the loop, which would make the whole thing atomic (rather than risking getting the first 4 of 8 days saved, then an error):

...
for (var date = fd; date <= td; date = date.AddDays(1))
{
    ...
}
db.SaveChanges();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!