属性"ID"是对象键信息的一部分,不能在asp.net mvc中进行修改 [英] The property 'ID' is part of the object's key information and cannot be modified in asp.net mvc

查看:144
本文介绍了属性"ID"是对象键信息的一部分,不能在asp.net mvc中进行修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将实体框架与代码优先方法结合使用.

I have used entity framework with code first approach.

当我尝试一次将记录从Fromdate传递到Todate时,这是它的工作第一次,它给出如下错误之后:属性'ID'是对象键信息的一部分,无法修改."

when I am trying to pass record one by one Fromdate to Todate, 1st time its work, after it gives error like: "The property 'ID' is part of the object's key information and cannot be modified."

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

       for (var date = fd; date <= td; date = date.AddDays(1))
        {
            var product = db.Products.Find(todaycooked.ProductID);
            product.Qty = product.Qty + todaycooked.QTY;
            todaycooked.Product = product;
            todaycooked.CookDate = date;
            db.TodayCookeds.Add(todaycooked);
            db.SaveChanges();
        }

预先感谢.

推荐答案

您每天设置一次ProductCookDate,所以我假设您每天要记录一次-表示您每天要说一个 object .我怀疑您实际上想要这样的东西:

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();
}

但是,您也可以将db.SaveChanges()移至循环的外部,这将使整个过程变得原子化(而不是冒着获得保存的8天中的第4天的风险,然后是一个错误):

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();

这篇关于属性"ID"是对象键信息的一部分,不能在asp.net mvc中进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆