![](/img/trans.png)
[英]How to make this base class work with Entity Framework 6.1 code first
[英]Entity Framework Code First - objects all inherit base class, how to exclude records with a disabled property
我有一堆DTO對象,它們都從DtoBase類繼承,並具有一些屬性,例如Id,CreatedDate和Disabled。
public class MyAppContext : ApplicationDbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
}
public class A : Base
{
public bool LikesMilk { get; set; }
}
public class B : Base
{
public string Name { get; set; }
}
public class Base
{
public int Id { get; set; }
public bool Disabled { get; set; }
}
在查詢數據庫時,是否有擴展方法或我可以寫的東西來排除所有對象的所有查詢上的所有禁用記錄?
//both should exclude disabled records
db.As.FirstOrDefault(x => x.LikesMilk)
db.Bs.ToList()
我已經完成了本文概述的相同方法。 http://www.codeguru.com/csharp/csharp/soft-deleting-entities-cleanly-using-entity-framework-6-interceptors.html
本質上,您創建一個屬性來將一列指定為“ IsDeleted”列(在您的情況下為“已禁用”)。 然后,您創建一個執行以下兩項操作的攔截器:
我最終使用了這個NuGet包EntityFramework.DynamicFilters,它真的很容易實現。 https://www.nuget.org/packages/EntityFramework.DynamicFilters
using EntityFramework.DynamicFilters;
public class MyAppContext : ApplicationDbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Filter("IsDisabled", (Base x) => x.Disabled, false);
}
}
public class A : Base
{
public bool LikesMilk { get; set; }
}
public class B : Base
{
public string Name { get; set; }
}
public class Base
{
public int Id { get; set; }
public bool Disabled { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.