CSharp · Console
// Entity Framework Plus
// Doc: https://entityframework-plus.net/query-filter
// @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();
using (var context = new EntityContext())
{
int myCategoryID = 1;
// CREATE filter by interface
context.Filter<Product>(q => q.Where(x => x.CategoryId == myCategoryID));
// SELECT * FROM Product WHERE CategoryID = 1
var products = context.Products.ToList();
FiddleHelper.WriteTable(products);
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Categories.Add(new Category() { Name = "Category_A" });
context.Categories.Add(new Category() { Name = "Category_B" });
context.Products.Add(new Product() { Name = "Product_A", CategoryId = 1 });
context.Products.Add(new Product() { Name = "Product_B", CategoryId = 2 });
context.Products.Add(new Product() { Name = "Product_C", CategoryId = 1 });
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<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
}