CSharp · Console
// Entity Framework Extensions
// Doc: https://entityframework-extensions.net/delete-from-query
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
public class Program
{
public static async Task Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
GenerateData();
using (var context = new EntityContext())
{
// INSERT only specific customers into the "bck_Customer" table
var ids = new List<int>() { 1, 2 };
await context.Customers
.WhereBulkContains(ids)
.InsertFromQueryAsync("bck_Customer", x => new { x.CustomerID, x.Name, x.Email });
// Only "Jonathan" and "Sales" should appear
FiddleHelper.WriteTable("bck_Customer", context.BackupCustomers.AsNoTracking().ToList());
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Customers.Add(new Customer() { Name = "Jonathan", Email = "[email protected]", IsActive = true, LastLogin = DateTime.Now.AddYears(-3) });
context.Customers.Add(new Customer() { Name = "Sales", Email = "[email protected]", IsActive = false, LastLogin = DateTime.Now.AddYears(-3) });
context.Customers.Add(new Customer() { Name = "Sara", Email = "[email protected]", IsActive = true, LastLogin = DateTime.Now });
context.BulkSaveChanges();
}
}
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 DbSet<BackupCustomer> BackupCustomers { get; set; }
}
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime LastLogin { get; set; }
public Boolean IsActive { get; set; }
}
[Table("bck_Customer")]
public class BackupCustomer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CustomerID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}