What I am looking for is to improve or to know if there is a different way to edit the elements of a list to later be stored in the database, I am currently using LINQ in C#, here I leave the code waiting for your help.
public bool DestroyItems(int userID, long projectID, int disciplineID)
{
try
{
using (var db = new buildbinderEntities())
{
// obtengo la lista
var updateElements = db.ContractItems.Where(w => w.ProjectID == projectID && w.DisciplineID == disciplineID).ToList();
// recorro la lista para modificar cada elemento por separado
foreach (var update in updateElements)
{
update.DeletedFlag = true;
update.DeletedDate = DateTime.Now;
update.DeletedUser = userID;
db.ContractItems.Attach(update);
db.Entry(update).State = EntityState.Modified;
db.SaveChanges();
}
}
return true;
}
catch (Exception)
{
return false;
}
}
You can make use of the EntityFramework.Extended library in Nuget EntityFramework.Extended to create a batch update .
In this way you are avoiding making N+1 calls to the database to make the update, but when it is executed, a
UPDATE
with a is createdWHERE
directly without the need to go through itSELECT
or doforeach
If you perform the operation within the EF context, the entity is still being tracked so you don't need the
Attach
orEntry(update).State = EntityState.Modified;
you can do it directly
You can also do the
SaveChanges()
at the end when you have updated all the entities