Search code examples
mergeentity-framework-coreentity-framework-extensions

Z.EntityFramework.Extensions.EFCore BulkMerge - Non Key Indexing to Update Records on Mass


I have a situation where I require to update records on mass. However, mytable is built to be quite dynamic and it's primary key is DBGenerated. I was wondering if anyone has used EF Extensions to accomplish the update based on other fields. I have tried the below from their documentation but it doesn't map and just reinserts the lot again. I have tried to modify the options several times and not had much success. I need to map the 'update-keys' as three other columns, keeping the original PK. Anyone able to suggest a better route whilst maintaining speed? .. I don't really want to loop and manually update each one at a time

https://bulk-operations.net/bulk-merge

await _db.Enotes.BulkMergeAsync(orderEnotes, operation =>
{
    operation.AutoMapKeyExpression = prop => new { prop.Entity, prop.EnoteType, prop.KeyValue1 };
    operation.InsertIfNotExists = true;
    operation.InsertKeepIdentity = false;
});

Class

public class EnoteEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Int64 EnoteID { get; set; }

        public string Entity { get; set; }

        public string EnoteType { get; set; }

        public string KeyValue1 { get; set; }

        public string KeyValue2 { get; set; }

Code removed for brevity... 

Solution

  • You currently use the library Entity Framework Extensions but you are looking at the Bulk Operations documentation so there is some difference.

    Here is the right documentation about Bulk Merge: https://entityframework-extensions.net/bulk-merge

    As you will find out, you should not use AutoMapKeyExpression but ColumnPrimaryKeyExpression to specify a custom key (Online Example):

    await _db.Enotes.BulkMergeAsync(orderEnotes, operation =>
    {
        operation.ColumnPrimaryKeyExpression = prop => new { prop.Entity, prop.EnoteType, prop.KeyValue1 };
    });
    

    In addition,

    The option InsertIfNotExists is only for the BulkInsert and InsertKeepIdentity is already false by default.