EF Extensions - Home - Main Features - Bulk Contains

CSharp · Console

/Program.cs

// Entity Framework Extensions - Main Features - Bulk Contains
// Doc: https://entityframework-extensions.net/

// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.Data.SqlClient;
					
public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		// SEED database
		using (var context = new EntityContext())
		{
			context.Customers.Add(new Customer() { Code = $"Info", Name = "Support Team", Email = "[email protected]" });
			context.Customers.Add(new Customer() { Code = $"Sales", Name = "Sales Team", Email = "[email protected]" });
			context.BulkSaveChanges();
			
			FiddleHelper.WriteTable("1 - Customers", context.Customers.ToList());			
		}
		
		// Return customers from the database matching customers from the list
		using (var context = new EntityContext())
		{
			var listCustomers = new List<Customer>() { new Customer() { CustomerID = 1 }, new Customer() { CustomerID = 3 }};
			
			var databaseCustomers = context.Customers.WhereBulkContains(listCustomers).ToList();
			
			FiddleHelper.WriteTable("2 - Database Customers", databaseCustomers);		
		}
		
		// Return customers from the list matching customers from the database
		using (var context = new EntityContext())
		{
			var listCustomers = new List<Customer>() { new Customer() { Name = "Sales Team", Email = "[email protected]" }, new Customer() { Name = "Random", Email = "Random" }};
			
			var sourceCustomers = context.Customers
				.WhereBulkContainsFilterList(listCustomers, x => new { x.Email, x.Name }).ToList();
			
			FiddleHelper.WriteTable("3 - Source Customers", sourceCustomers);		
		}
	}

	public class EntityContext : DbContext
	{
		public EntityContext() 
		{
		}
		
		public DbSet<Customer> Customers { get; set; }
		
		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));

			base.OnConfiguring(optionsBuilder);
		}
	}

	public class Customer
	{
		public int CustomerID { get; set; }
		public string Code { get; set; }
		public string Name { get; set; }
		public string Email { get; set; }
	}
}
;