我的大多数实体(并非全部)都有两个名为CompanyId
和Deleted
的属性。如何为所有选择请求自动插入这两个属性,而不是手动设置我在整个应用程序中的每个查询。
示例:
db.MyEntity.Where(me => me.Id == 1).Select(me => me.Description)
CompanyId
和Deleted
。 db.MyEntity.Where(me => me.Id == 1 && Deleted == false && CompanyId == 1).Select(me => me.Description
)
这将有助于我将这些条件设置为具有可用属性的所有查询。
答案 0 :(得分:4)
您可以在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