LINQ to Entities updating multiple rows
I am new to LINQ to Entities and need some guidance about how to think about multiple row updates. My problem is actually more conceptual than syntactical as I am not sure if I am even thinking about the solution correctly.
Here is a single row update. This seems very straightforward.
products prodtbl = (from p in db.products where p.product_id == 1 select p).First();
prodtbl.product_name = "Blueberry Jam";
db.SaveChanges();
The problem occurs when I wish to update multiple rows (e.g. remove the where claus开发者_JS百科e). Then prodtbl is not addressable as a list. If I want to see the product name of the 10th row is the only way to do this as follows?
'List<type> prodlist = prodtbl.ToList<type>()';
string name = prodlist[9].product_name
Now, if I change prodlist[9].product_name, how do I update the original row in prodtbl? Since prodtbl is not addressable as an array I can't just set it, can I? Do I have to create a LINQ statement with a where clause that only updates the single record? If the answer is 'yes, is there a batch update method if I have changed multiple rows?
You don't need to create separate statements.
You can use, e.g.:
prodtbl.ElementAt(9).product_name = "Bob";
Or iterate:
foreach (var p in prodtbl)
{
p.product_name = "New name";
}
You can perform this action as follows,
var objTrn = context.Trn_Dependent.Where(i => i.DependentID == DependentId).ToList();
objTrn.ForEach(x => { x.IsDeleted = true; x.UpdatedBy = objUserInfo.EnrolleeID.ToString(); x.UpdatedOn = DateTime.Now; });
objTrn.ForEach(p => context.Entry(p).State = EntityState.Modified);
context.SaveChanges();
精彩评论