EF.Plus - Batch Update - ALL (EF Core)

CSharp · Console

/Program.cs

// Entity Framework Plus
// Doc: https://entityframework-plus.net/batch-update

// @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();
		
		// Update: UPDATE all rows from the database using a LINQ Query without loading entities in the context.
		using (var context = new EntityContext())
		{
			// UPDATE all customers that are inactive for more than two years
			context.Customers
				.Update(x => new Customer {IsActive = false, Description = "Updated"});
			
			FiddleHelper.WriteTable(context.Customers.ToList());	
		}
	}
		 
	public static void GenerateData()
	{
		
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Name ="Customer_A", Description = "Description", IsActive = true, LastLogin = new DateTime(2010,1,1) });
			context.Customers.Add(new Customer() { Name ="Customer_B", Description = "Description", IsActive = true, LastLogin = new DateTime(2010,1,1) });			
			context.Customers.Add(new Customer() { Name ="Customer_C", Description = "Description", IsActive = true, LastLogin = DateTime.Now });
			
			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 string Description { get; set; }
		public DateTime LastLogin { get; set; }
		public Boolean IsActive { get; set; }
	}
}
;