Is there any way to run an update statement when using the BulkMerge of Entity Framework Extensions? For instance, if the record exists, sum the current value in the database plus the value in the parameter list. If the record doest exists then just insert the value of the parameter list in the database.
I'm looking for something to include like (x => new Animal {Age = x.Age + parameters.Age});
In terms of SQL it would be something like this merge:
WHEN MATCHED THEN
UPDATE SET
TARGET.ColumNumber = TARGET.ColumNumber + SOURCE.ColumNumber
WHEN NOT MATCHED BY TARGET THEN
INSERT...
Yes, it's possible to add an hardcoded formula.
Here is an example by using PostConfiguration: https://dotnetfiddle.net/s8QF4t
context.BulkMerge(list, options => {
options.PostConfiguration = bulk => {
bulk.ColumnMappings.Single(x => x.SourceName == "Description").FormulaUpdate = "DestinationTable.Name + ';' + StagingTable.Description";
};
});
Here is an example by mapping all your columns: https://dotnetfiddle.net/enOEQF
context.BulkMerge(list, options => {
options.ColumnMappings.Add(new Z.BulkOperations.ColumnMapping<Customer>(x => x.CustomerID, true));
options.ColumnMappings.Add(new Z.BulkOperations.ColumnMapping<Customer>(x => x.Name));
var columnMapping = new Z.BulkOperations.ColumnMapping<Customer>(x => x.Description);
columnMapping.FormulaUpdate = "DestinationTable.Name + ';' + StagingTable.Description";
options.ColumnMappings.Add(columnMapping);
});
Both examples concatenate 2 fields but as you see, you can use any kind of Formula. It's important to use the DestinationTable
and StagingTable
alias
The DestinationTable is the table on which the data will be updated. So the TARGET
table in your example.
The StagingTable is the table on which data is taken from for the update. So the SOURCE
table in your example.