Search code examples
c#entity-framework-coreentity-framework-extensions

Does BulkMerge update the provided entity objects?


I use efcore and entity framework extensions.

I have a requirement where I need to mass update-or-insert data, and then returned the updated/inserted data to the UI. The data have a database autogenerated GUID.

With the classic way I get the id after calling save changes.

var recipient = new RecipientEntity { name = '...', last_name = '...', ... };

dbContext.Recipients.Add(recipient);

// here the recipient id is empty

dbContext.SaveChanges();

// here the recipient id has value, the one generated by the db server.

When I use BulkMerge is there a way to get back the actual inserted entities?

var recipientsToMerge = new List<RecipientEntity>{
   new Recipient{ id = '234134134', name = '...', ... }, // this recipient has an id, it should be updated
   new Recipient{ name = '...', ... } // no id, it should be inserted
   new Recipient{ name = '...', ... } // no id, it should be inserted
};

dbContext.BulkMerge(recipientsToMerge);

// if I access the recipientsToMerge list here, will it contain the values after the merge?


Solution

  • The BulkMerge method from EF Extensions library indeed returns the Identity/GUID value generated by the database.

    Here is an example that shows the identity has been returned after the BulkMerge: https://dotnetfiddle.net/7jZUoM