简体   繁体   中英

Best Update Perfomance with Entity Framework

I am using the Entity Framework 6.1.3. I have a list ob objects (same properties like the database table) How can I reach the best perfomance while doing the update statements?

While perfoming any Insert action I could use the AddRange() Method to Insert all Items of the List. is there a possibilty to do this as well on update statements?

At the Moment I'll do a foreach on the list, and then I call the update method:

 public void UpdateZeitenPaar(int? pc_c_mandant_id, int? pc_d_zeiten_id, int pc_d_zeiten_paare_id, string personalnummer, DateTime? kommZeit, DateTime? gehZeit, int? kommID, int? gehID, decimal? zeitIst, decimal? zeitPause, int? pc_d_aktivitaet_id, DateTime? datum)
    {
        pc_d_zeiten_paare paar = db.pc_d_zeiten_paare.SingleOrDefault(p => p.pc_c_mandant_id == pc_c_mandant_id && p.pc_d_zeiten_paare_id == pc_d_zeiten_paare_id);
        paar.datum = datum;
        paar.gehZeit = gehZeit;
        paar.geh_pc_d_buchungsdaten_id = gehID;
        paar.kommZeit = kommZeit;
        paar.komm_pc_d_buchungsdaten_id = kommID;
        paar.pc_c_mandant_id = pc_c_mandant_id;
        paar.pc_d_aktivitaet_id = pc_d_aktivitaet_id;
        paar.pc_d_zeiten_id = pc_d_zeiten_id;
        paar.personalnummer = personalnummer;
        paar.zeitIst = zeitIst;
        paar.zeitPause = zeitPause;
        db.SaveChanges();
    }

EF creates on SaveChanges for each data-manipulation on a object a separate query. Even a deletion of multiple objects results in a creation of multiple DELETE queries. You can improve the UI Response time by using async/await :

public async Task UpdateZeitenPaar()
{
    var paar = await db.pc_d_zeiten_paar.SingleOrDefaultAsync(...);
    // [...]
    await db.SaveChangesAsync();
}

You are getting the item on every update call, this is most likely your problem.

pc_d_zeiten_paare paar = db.pc_d_zeiten_paare.SingleOrDefault(p => p.pc_c_mandant_id == pc_c_mandant_id && p.pc_d_zeiten_paare_id == pc_d_zeiten_paare_id);

You are most likely looping through your items with a foreach calling this method and have the id parameter in some collection. You could try to eager loading all entities at once to memory that you are going to update.

// This will load all the instances to the context, so they are already in the memory and no round trip to db is required
// Assuming your myItemList is the list that contains your item types and the id's of the items you are going to update
var materializedList = db.pc_d_zeiten_paare.Where(p => myItemList.Any(myp => myp.pc_d_zeiten_paare_id == p.pc_d_zeiten_paare_id).ToList();

// do your normal update logic here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM