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

后端 未结 1 664
名媛妹妹
名媛妹妹 2021-01-14 18:08

I have used entity framework with code first approach.

when I am trying to pass record one by one Fromdate to Todate, 1st time its work, after it gives error like: \

1条回答
  •  生来不讨喜
    2021-01-14 18:19

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

    0 讨论(0)
提交回复
热议问题