Does BulkMerge update the provided entity objects?

171 views Asked by At

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?

2

There are 2 answers

0
Jonathan Magnan On BEST ANSWER

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

0
Svyatoslav Danyliv On

I would suggest to us other extension for such task linq2db.EntityFrameworkCore (note that I'm one of the creators)

Then you can do the following:

var mergedRecipients = dbContext.Recipients.ToLinqToDBTable()
    .Merge()
    .Using(recipientsToMerge)
    .OnTargetKey()
    .InsertWhenNotMatched()
    .UpdateWhenMatched()
    .MergeWithOutput((action, deleted, inserted) => inserted)
    .ToList();

mergedRecipients should contain full new/updated records. If you do not need whole record, you can simplify projection.