Best way to connect and update properties using Entity Framework 5

I have an action method that gets a list of items containing updated values. The fact is that I only want to update a couple of fields (by e-mail or by phone), and not by full recording. The code below seems to do what I need, but is there a better or updated way to do this using EF 5? Sometimes I see people using .Find instead of Attach, etc.

public ActionResult Update(IEnumerable<GenericTable> items) { using (var gEntities = new genericEntities()) { foreach (var GenericTable in items) { gEntities.GenericTable.Attach(GenericTable); gEntities.Entry(GenericTable).Property(x => x.EmailAddress).IsModified = true; gEntities.Entry(GenericTable).Property(x => x.PhoneNumber).IsModified = true; } gEntities.SaveChanges(); } 

Here I directly indicate the EF email address. And the phone number changes every time, but in practice it is one or the other, is there a way to detect only changed columns / properties?

thanks

+4
source share
1 answer

The application is perfect for your purposes if you no longer have one of these GenericTable elements in context, in which case it will throw an exception. Find the search for the record in the context, and if it does not find it, it queries the database for this record and returns it (so it attaches it to the process).

I would set a modified flag for the whole table as follows:

 foreach (var table in items) { gEntities.GenericTable.Attach(table); gEntities.Entry<GenericTable>(table).State = EntityState.Modified; } 

EF checks which property is modified and updated accordingly when you call SaveChanges ().

+2
source

Source: https://habr.com/ru/post/1497075/


All Articles