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