0

I'm using EF 5.0 and Code First. In my generic repository I have a method for exclude records in a logical way. This method actually perform a update, setting the status of the entity field to false.

I would like to intercept my queries, and filter only where status == true.

Is there a easy way to do that? Ex:

new GenericRepository<Entity>().ToList(); 
// and internally it will filter where status == true.
4

3 回答 3

2

你可以让你的所有实体实现一些IDeletable接口:

public interface IDelitable
{
    bool IsDeleted { get; }
}

并将约束添加到存储库的通用参数

public class GenericRepository<T>
   where T: class, IDelitable

并在返回值时添加过滤器:

context.Set<T>().Where(e => !e.IsDeleted)
于 2013-07-12T11:36:37.300 回答
2

创建一个泛型方法

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);
   } 
于 2013-07-12T11:49:30.647 回答
0

您可以使用 Where 过滤它。

.Where(e => e.Status == true).ToList();
于 2013-07-12T11:37:39.190 回答