CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/matched-and-one-not-condition
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Z.BulkOperations;
public class Program
{
public static void Main()
{
// SCENARIO: https://entityframework-extensions.net/matched-and-one-not-condition
// CREATE & SEED
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
var customers = new List<Customer>();
customers.Add(new Customer() { CustomerID = 1, Name = "Jonathan", Email = "Email_Jonathan", Note = "Note_Jonathan" });
customers.Add(new Customer() { CustomerID = 2, Name = "Mikael", Email = "Email_Mikael", Note = "Note_Mikael" });
customers.Add(new Customer() { CustomerID = 3, Name = "Sara", Email = "Email_Sara", Note = "Note_Sara" });
context.BulkInsert(customers, options => { options.InsertKeepIdentity = true; });
FiddleHelper.WriteTable("1 - Before BulkSynchronize", context.Customers.ToList());
}
using (var context = new EntityContext())
{
var customers = new List<Customer>();
// DATA coming from an importation
// "Jonathan" only have the "Note" property updated
customers.Add(new Customer() { CustomerID = 1, Name = "Jonathan", Email = "Email_Jonathan", Note = "Note_Jonathan (Updated)" });
customers.Add(new Customer() { CustomerID = 2, Name = "Mikael (Updated)", Email = "Email_Mikael (Updated)", Note = "Note_Mikael (Updated)" });
customers.Add(new Customer() { CustomerID = 3, Name = "Sara (Updated)", Email = "Email_Sara (Updated)", Note = "Note_Sara (Updated)" });
context.BulkSynchronize(customers, options =>
{
// ON UPDATE, modify the customer if a values for "Name" or "Email" is different
options.SynchronizeMatchedAndOneNotConditionExpression = x => new { x.Name, x.Email };
});
FiddleHelper.WriteTable("2 - After BulkSynchronize", context.Customers.AsNoTracking().ToList());
}
}
public class EntityContext : DbContext
{
public EntityContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Note { get; set; }
}
}