More efficient way to perform a UPSERT with EF6

c# entity-framework-6

Accepted Answer

The EF's creators have left working with detached entities up to the developers that use it. Since everything relies on the user case and the entity model, there is no "correct" method to do anything.

Since it seems that you're need updates to the current records (by changing theDateModified ), it is unnecessary to import the current data into context. To create or change an entity, it would be sufficient to get the current entity PKs with a single database trip and utilise them as criteria:

using (var db = new Entities.DB.DConn())
    var accountIds = accounts.Select(x => x.GId); // variable required by EF6 Contains translation
    var existingAccountIds = new HashSet<GId_Type>(
        db.Accouns.Where(x => accountIds.Contains(x.GId).Select(x => x.GId));
    foreach (Account account in accounts)
        var dlAccount = new Entities.DB.Account();
        dlAccount.GId = account.GId;
        dlAccount.AccountName = account.NameAtFI;
        dlAccount.AccountNumber = account.AcctNumber;
        dlAccount.AcctType = account.AcctType;
        dlAccount.AsOfDate = account.DateCreated;
        dlAccount.IsDeleted = false;
        dlAccount.DateModified = DateTime.UtcNow.ToUniversalTime();    
        if (existingAccountIds.Contains(dlAccount.GId))
            db.Entry(dlAccount).State = EntityState.Modified; // update
            db.Accounts.Add(dlAccount); // insert

(Insert theGId_Type Using the kind ofGId , , Guid etc.)

In addition to shifting theSaveChanges The best performance in this case should come from outside the loop.

7/13/2017 5:56:35 PM

Expert Answer

7/13/2017 7:15:20 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow