optimizaefcore - ExecuteDelete

CSharp · Console

/Program.cs

// @nuget: Microsoft.EntityFrameworkCore.SqlServer

using System;
using System.Linq;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("=== ExecuteDelete en EF Core - Demo interactiva ===\n");

        using var context = new AppDbContext();
		
		Console.WriteLine("=== Crear base de datos ===\n");
		context.Database.EnsureCreated();
		
        // Aseguramos datos semilla
        SeedIfNeeded(context);

        Console.WriteLine(">> Empleados ANTES de ExecuteDelete (CompanyId = 1):\n");
        PrintEmployees(context);

        // Operación set-based con ExecuteDelete
        Console.WriteLine("\nAplicando ExecuteDelete: eliminando empleados inactivos de CompanyId = 1...\n");

        var rows = context.Employees
            .Where(e => e.CompanyId == 1 && !e.IsActive)
            .ExecuteDelete();

        Console.WriteLine($">> Filas eliminadas: {rows}\n");

        Console.WriteLine(">> Empleados DESPUÉS de ExecuteDelete (CompanyId = 1):\n");
        PrintEmployees(context);
    }

    private static void SeedIfNeeded(AppDbContext context)
    {
        if (context.Employees.Any())
            return;

        context.Employees.AddRange(
            new Employee { CompanyId = 1, Name = "Alice", Salary = 1000m, IsActive = false, UpdatedAt = DateTime.UtcNow.AddDays(-30) },
            new Employee { CompanyId = 1, Name = "Bob",   Salary = 1200m, IsActive = true,  UpdatedAt = DateTime.UtcNow.AddDays(-10) },
            new Employee { CompanyId = 1, Name = "Carol", Salary = 1300m, IsActive = false, UpdatedAt = DateTime.UtcNow.AddDays(-90) },
            new Employee { CompanyId = 2, Name = "Daniel",Salary = 1500m, IsActive = true,  UpdatedAt = DateTime.UtcNow.AddDays(-5) }
        );

        context.SaveChanges();
    }

    private static void PrintEmployees(AppDbContext context)
    {
        var employees = context.Employees
            .Where(e => e.CompanyId == 1)
            .OrderBy(e => e.Id)
            .ToList();

        foreach (var e in employees)
        {
            Console.WriteLine(
                $"Id: {e.Id}, Name: {e.Name}, Salary: {e.Salary:F2}, IsActive: {e.IsActive}, UpdatedAt: {e.UpdatedAt:O}");
        }
    }
}

public class Employee
{
    public int Id { get; set; }
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public bool IsActive { get; set; }
    public DateTime UpdatedAt { get; set; }
}

public class AppDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
}
;