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 myApplicationID = 9;
int myCustomerID = 2;
// CREATE filter by interface
context.Filter<IApplication>(q => q.Where(x => x.ApplicationId == myApplicationID));
// SELECT * FROM Invoice WHERE ApplicationID = 9 and CustomerID = 2
var list = context.Invoices.Where(x => x.CustomerId == myCustomerID).ToList();
FiddleHelper.WriteTable(list);
}
}
public static void GenerateData()
{
using (var context = new EntityContext())
{
context.Customers.Add(new Customer() { Name = "Customer_A", ApplicationId = 3 });
context.Customers.Add(new Customer() { Name = "Customer_B", ApplicationId = 9 });
context.Customers.Add(new Customer() { Name = "Customer_B", ApplicationId = 5 });
context.Invoices.Add(new Invoice() { Date = DateTime.Now.AddDays(-3), CustomerId = 1 });
context.Invoices.Add(new Invoice() { Date = DateTime.Now.AddDays(4), CustomerId = 2 });
context.Invoices.Add(new Invoice() { Date = DateTime.Now.AddDays(1), CustomerId = 2 });
context.Invoices.Add(new Invoice() { Date = DateTime.Now.AddDays(1), CustomerId = 3 });
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<Customer> Customers { get; set; }
public DbSet<Invoice> Invoices { get; set; }
}
public interface IApplication
{
int ApplicationId { get; set; }
}
public class Customer : IApplication
{
public int CustomerId { get; set; }
public string Name { get; set; }
public int ApplicationId { get; set; }
public List<Invoice> Invoices { get; set; }
}
public class Invoice
{
public int InvoiceId { get; set; }
public DateTime Date { get; set; }
public int CustomerId { get; set; }
}
}