CSharp · Console
// Entity Framework Plus
// Doc: https://entityframework-plus.net/query-include-optimized
// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Plus.EFCore
using System;
using System.Linq;
using Z.EntityFramework.Plus;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
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())
{
// LOAD orders and the first 10 active related entities.
var list = context.Orders.IncludeOptimized(x => x.Items).ToList();
foreach(var order in list)
{
Console.WriteLine("Order items in {0}: {1}", order.Name, order.Items.Count());
}
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Orders.Add(new Order() { Name = "Order_A", Date = DateTime.Now.AddDays(-4), IsSoftDeleted = true });
context.Orders.Add(new Order() { Name = "Order_B", Date = DateTime.Now.AddDays(-5), IsSoftDeleted = true });
context.SaveChanges();
context.Items.Add(new OrderItem() { Date = DateTime.Now.AddDays(-4), IsSoftDeleted = false, Price = 35, OrderId = 1 });
context.Items.Add(new OrderItem() { Date = DateTime.Now.AddDays(-4), IsSoftDeleted = false, Price = 22, OrderId = 1 });
context.Items.Add(new OrderItem() { Date = DateTime.Now.AddDays(-5), IsSoftDeleted = false, Price = 37, OrderId = 2 });
context.Items.Add(new OrderItem() { Date = DateTime.Now.AddDays(-5), IsSoftDeleted = true, Price = 7, OrderId = 2 });
context.SaveChanges();
}
}
public class EntityContext : DbContext
{
public EntityContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
}
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> Items { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public bool IsSoftDeleted { get; set; }
public List<OrderItem> Items { get; set; }
}
public class OrderItem
{
public int OrderItemId { get; set; }
public DateTime Date { get; set; }
public bool IsSoftDeleted { get; set; }
public int Price { get; set; }
public int OrderId { get; set; }
}
}