我的上下文类中有一个DbSet属性,如下所示:
public class ProjectContext: DbContext { public ProjectContext(): base("name=DBCS") { } public DbSet<Employee> EmployeeDbSet { get; set; } }此属性正在我的项目的许多地方使用。 现在我需要在Employee上设置一个通用条件,例如我只需要活跃的员工。 我可以通过简单地过滤我的linq查询来获得活跃的员工:
var employees = context.EmployeeDbSet.where(e => e.IsActive).ToList();由于我已经在我的项目的许多地方编写了许多查询,现在我必须重写它们,这非常困难,耗时且容易出错。
由于这是一个通用条件,我想在所有查询上设置它,我正在寻找一种方法来设置EmployeeDbSet属性的条件。
可以完成吗?
谢谢你的帮助
I have a DbSet property in my context class as follows:
public class ProjectContext: DbContext { public ProjectContext(): base("name=DBCS") { } public DbSet<Employee> EmployeeDbSet { get; set; } }This property is being used in many places of my project. Now I need to set a generic condition on Employee such as I need only active employees. I can get active employees by simply filtering my linq queries like this:
var employees = context.EmployeeDbSet.where(e => e.IsActive).ToList();Since I've already written many queries in many places of my project, now I have to rewrite them all which is very difficult, time-consuming and error prone.
As this is a generic condition and I want to set this on all queries, I'm looking for a way to set the condition on EmployeeDbSet property instead.
Can it be accomplished?
Thanks for any help
最满意答案
您可以向DbContext添加IQueryable<Employee>属性,该属性返回活动where where条件集。
例;
public IQueryable<Employee> ActiveEmployees { get { return EmployeeDbSet.Where(e => e.IsActive); } }通过这种方式,您可以将其与其他条件相结合;
context.ActiveEmployees.Where(x=> x.name == "john");执行此操作后,您无法使用直接在DbSet<T>中声明的方法。 要在使用where之后使用find方法,您可以自己添加一个新的find方法,如下所示;
public static class DbModelExtensions { public static Employee Find(this IQueryable<Employee> query, int id) { return query.Where(x => x.Id == id).FirstOrDefault(); } }如果在当前文件中引用其名称空间,则会添加一个扩展方法Find to only IQueryable<Employee> 。
然后就可以像这样使用它;
context.ActiveEmployees.Find(15);You can add a IQueryable<Employee> property to your DbContext that returns the active where condition set.
Example;
public IQueryable<Employee> ActiveEmployees { get { return EmployeeDbSet.Where(e => e.IsActive); } }This way you can combine it with other where conditions by just doing;
context.ActiveEmployees.Where(x=> x.name == "john");After you do this you cant use methods that declared directly in DbSet<T>. To use find method after you use where, You can add a new find method yourself as follows;
public static class DbModelExtensions { public static Employee Find(this IQueryable<Employee> query, int id) { return query.Where(x => x.Id == id).FirstOrDefault(); } }This adds a extension method Find to only IQueryable<Employee> if its namespace is referenced in current file.
Then you can use it like this;
context.ActiveEmployees.Find(15);更多推荐
发布评论