将 Where 条件添加到所有请求 EF6

Adding Where Condition to All Requests EF6

我的大多数实体 (不是全部) 有两个属性,分别称为 CompanyIdDeleted。如何为所有 select 请求自动插入这两个属性,而不是在整个应用程序的每个查询中手动设置。

示例:

db.MyEntity.Where(me => me.Id == 1).Select(me => me.Description)

db.MyEntity.Where(me => me.Id == 1 && Deleted == false && CompanyId == 1).Select(me => me.Description)

这将有助于我为所有具有可用属性的查询设置这些条件。

您可以在 nuget 包的帮助下添加过滤器:EntityFramework.Filters。另外,创建通用接口而不是动态检查属性是否存在是个好主意:

public interface IMyEntityInterface
{
    public int Id {get;set;}
    public bool Deleted {get;set;}
}

public class MyEntity : IMyEntityInterface
{
    public int Id {get;set;}
    public bool Deleted {get;set;}
    //other stuff
}

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{   
    modelBuilder.Conventions
       .Add(FilterConvention.Create<IMyEntityInterface, int, bool>("MyFilter", (entity, Id, Deleted) => entity.Id == Id && entity.Deleted == Deleted);
}

用法:

var filter = db.EnableFilter("MyFilter");
filter.SetParameter("Id", 1);
filter.SetParameter("Deleted", false);

var data = db.MyEntity.Where(me => me.CompanyId == 1).Select(me => me.Description);
//select Description from MyEntities where Id = 1 and Deleted = false and CompanyId = 1