Code Firtst 如何设置默认查询条件
我的所以业务实体中都有一个属性OrgCode(机构代码),我想在所有基于实体框架查询时,不用显式加入对这个字段的查询条件,而是由框架自动实现,可不可以实现?
如:
using (DBContext context = new DBContext())
{
return context.Roles.Where(r => r.OrgCode == orgCode).ToList();
}
using (DBContext context = new DBContext())
{
return context.Roles.ToList();
}
public static class EntitiesFilterHelper
{
public static IEnumerable<T> AutoFilter<T>(this IEnumerable<T> entities)
{
HttpContext context = HttpContext.Current;
if (context == null)
throw new InvalidOperationException();
NameValueCollection queryString = context.Request.QueryString;
string[] queryKeys = queryString.AllKeys;
foreach (string key in queryKeys)
{
PropertyInfo property = typeof(T).GetProperty(key, BindingFlags.Public
[解决办法]
BindingFlags.Instance);
if (property == null)
continue;
entities = entities.Where(e =>
{
return property.GetValue(e, null).ToString() == queryString[key];
});
}
return entities;
}
}