optimizaefcore - ExecuteUpdate by ZZZ Projects

CSharp · Console

/Program.cs

// @nuget: Microsoft.EntityFrameworkCore
// @nuget: Microsoft.EntityFrameworkCore.Sqlite
// @nuget: Microsoft.EntityFrameworkCore.Relational

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

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

        using (var context = new AppDbContext())
        {
            // Crear base de datos y datos semilla
            context.Database.EnsureCreated();
            SeedIfNeeded(context);

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

            Console.WriteLine("\nAplicando ExecuteUpdate: +10% de salario y actualización de UpdatedAt...\n");

            var rows = context.Employees
                .Where(e => e.CompanyId == 1)
                .ExecuteUpdate(s => s
                    .SetProperty(e => e.Salary, e => e.Salary * 1.10m)
                    .SetProperty(e => e.UpdatedAt, DateTime.UtcNow));

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

        // ⚠️ Nuevo DbContext para reflejar cambios (sin Change Tracker)
        using (var freshContext = new AppDbContext())
        {
            Console.WriteLine(">> Salarios DESPUÉS de ExecuteUpdate (CompanyId = 1):\n");
            PrintEmployees(freshContext);
        }
    }

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

        context.Employees.AddRange(
            new Employee { CompanyId = 1, Name = "Alice", Salary = 1000m, UpdatedAt = DateTime.UtcNow.AddDays(-1) },
            new Employee { CompanyId = 1, Name = "Bob",   Salary = 1200m, UpdatedAt = DateTime.UtcNow.AddDays(-1) },
            new Employee { CompanyId = 2, Name = "Carol", Salary = 1500m, UpdatedAt = DateTime.UtcNow.AddDays(-1) }
        );

        context.SaveChanges();
    }

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

        foreach (var e in employees)
        {
            Console.WriteLine(
                $"Id: {e.Id}, Name: {e.Name}, Salary: {e.Salary:F2}, 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 DateTime UpdatedAt { get; set; }
}

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

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source=executeupdate_demo.db");
}
;