我正在使用EF 5.0和Code First。在我的通用存储库中,我有一种逻辑上排除记录的方法。此方法实际上执行更新,将实体字段的状态设置为false。
我想拦截我的查询,并仅在status == true的地方进行过滤。
有没有简单的方法可以做到这一点?前任:
new GenericRepository<Entity>().ToList();
// and internally it will filter where status == true.
创建一个通用方法
public IQueryable<T> All<T>(Expression<Func<T, bool>> predicate) {
return context.Set<T>().Where(predicate);
}
并且如果您想要更多与您的status
属性链接的东西,则必须使用反射并自己构建Lambda(因为您不能使用带有linq的接口来引发查询)。
诸如此类(未经测试),调用泛型All
方法。
public IQueryable<T>AllButDeleted<T>() {
var property = typeof(T).GetProperty("status");
//check if T has a "status" property
if (property == null && || property.PropertyType != typeof(bool)) throw new ArgumentException("This entity doesn't have an status property, or it's not a boolean");
//build the expression
//m =>
var parameter = new ParameterExpression(typeof(T), "m");
// m.status
Expression body = Expression.Property(parameter, property);
//m.status == true (which is just m.status)
body = Expression.IsTrue(body);
//m => m.status
var lambdaPredicate = Expression.Lambda<Func<T, bool>>(body, new[]{parameter});
return All(lambdaPredicate);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句