CSharp · Console
// Entity Framework Plus
// Doc: https://entityframework-plus.net/batch-delete
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Plus.EFCore
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using Z.EntityFramework.Plus;
public class Program
{
public static void Main()
{
using (var context = new EntityContext())
{
context.Database.EnsureCreated();
}
GenerateData();
// Delete: DELETE all rows from the database using a LINQ Query without loading entities in the context
using (var context = new EntityContext())
{
// DELETE all customers that are inactive
context.Customers.Where(x => !x.IsActive).Delete();
FiddleHelper.WriteTable(context.Customers.ToList());
}
// Delete: DELETE all rows from the database using a LINQ Query without loading entities in the context
using (var context = new EntityContext())
{
// DELETE customers by Name
context.Customers.Where(x => x.Name =="Customer_B").Delete();
FiddleHelper.WriteTable(context.Customers.ToList());
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Customers.Add(new Customer() { Name ="Customer_A", IsActive = false });
context.Customers.Add(new Customer() { Name ="Customer_B", IsActive = true });
context.Customers.Add(new Customer() { Name ="Customer_C", IsActive = false });
context.SaveChanges();
}
using (var context = new EntityContext())
{
FiddleHelper.WriteTable(context.Customers.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 Boolean IsActive { get; set; }
}
}