Skip to content

Instantly share code, notes, and snippets.

View JonathanMagnan's full-sized avatar

Jonathan Magnan JonathanMagnan

View GitHub Profile
using (var ctx = new CustomerContext())
{
foreach(var line in lines)
{
var customer = new Customer();
// ...code...
// DetectChanges is invoked every time you call Add
ctx.Customers.Add(customer);
}
using (var ctx = new CustomerContext())
{
foreach(var line in lines)
{
var customer = new Customer();
// ...code...
ctx.Customers.Add(customer);
}
ctx.SaveChanges();
using (var ctx = new CustomerContext())
{
// 1. SPLIT the queries in multiple smaller queries
var customers = ctx.Customers
.Include(x => x.Orders.Select(y => y.Items.Select(z => z.Product))
.ToList();
var customers = ctx.Customers
.Include(x => x.Payments.Select(y => y.Items)
.ToList();
using (var ctx = new CustomerContext())
{
List<Customer> customers = new List<Customer>();
foreach(var line in lines)
{
var customer = new Customer();
// ...code...
customers.Add(customer);
using (var ctx = new CustomerContext())
{
List<Customer> customers = new List<Customer>();
foreach(var line in lines)
{
var customer = new Customer();
// ...code...
customers.Add(customer);
// using Z.EntityFramework.Plus; // Don't forget to include this.
// AutoSave audit in a database
AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
(context as EntityContext).AuditEntries.AddRange(audit.Entries);
var ctx = new EntityContext();
// ... ctx changes ...
var audit = new Audit();
// using Z.EntityFramework.Plus; // Don't forget to include this.
// DELETE all users inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
.Delete();
// DELETE using a BatchSize
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
.Delete(x => x.BatchSize = 1000);
// using Z.EntityFramework.Plus; // Don't forget to include this.
// UPDATE all users inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
.Update(x => new User() { IsSoftDeleted = 1 });
// using Z.EntityFramework.Extensions; // Don't forget to include this.
// Easy to use
context.BulkDelete(list);
// Easy to customize
context.BulkDelete(list, bulk => bulk.BatchSize = 100);
// using Z.EntityFramework.Extensions; // Don't forget to include this.
// Easy to use
context.BulkInsert(list);
// Easy to customize
context.BulkInsert(list, bulk => bulk.BatchSize = 100);