Skip to content

Instantly share code, notes, and snippets.

@svick
Created November 20, 2021 09:21
Show Gist options
  • Save svick/f39ef913a584d182ad57dd36deafd3c1 to your computer and use it in GitHub Desktop.
Save svick/f39ef913a584d182ad57dd36deafd3c1 to your computer and use it in GitHub Desktop.
void Main()
{
using var context = new WarehouseContext();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var apple = new Product { Name = "Apple" };
var pear = new Product { Name = "Pear" };
context.Products.AddRange(apple, pear);
context.WarehouseStocks.Add(new() { Product = apple, Count = 1 });
context.SaveChanges();
var products = context.Products;
var warehouseStocks = context.WarehouseStocks;
var query =
from product in products
join warehouseStock in warehouseStocks on product.Id equals warehouseStock.ProductId into ws
from warehouseStock in ws.DefaultIfEmpty()
where (warehouseStock.Id == null)
select product;
query.ToQueryString().Dump();
query.Dump();
var query2 =
from product in products
join warehouseStock in warehouseStocks on product.Id equals warehouseStock.ProductId into ws
from warehouseStock in ws.DefaultIfEmpty()
where (warehouseStock == null)
select product;
query2.ToQueryString().Dump();
query2.Dump();
}
public class WarehouseContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<WarehouseStock> WarehouseStocks { get; set; }
public string DbPath { get; }
public WarehouseContext()
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
DbPath = Path.Join(path, "warehouse.db");
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={DbPath}");
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class WarehouseStock
{
public int Id { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
public int Count { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment