entity framework - How to Update a List of entities properly? -
i update list of entities, using ef4.
- i have viewmodel object (retrieved web form) passed method named "producttoupdate" contains list "labels".
i corresponding list of objects database linq query anonymous object named "requetevalslabels" did manually (testing id's in foreach loop) follow, imagine not best way it?
for (int = 0; < producttoupdate.labels.count; i++) { foreach (var item in producttoupdate.labels) { if (requetevalslabels[i].id == item.idvaleurlabel){ requetevalslabels[i].valeur = item.valeur; } } }
you may want use following pattern
foreach (var item in producttoupdate.labels) { entity e = new entity { id = item.idvaleurlabel}; context.entityset.attach(e); e.valeur = item.valeur; }
this prevent loading (select) trip database but:
- as no load occur, can't sure id exists in db, may have
an insertexception trying update non existing row. - as no load occur, can't check label modification , may update same value.
Comments
Post a Comment