LINQ的实体框架的通用滤波方法 [英] Linq Entity Framework generic filter method

查看:121
本文介绍了LINQ的实体框架的通用滤波方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些方法,从我的实体(使用实体框架V4)对数据执行标准过滤器

I have some methods which perform a standard filter on data from my Entities (using Entity Framework v4).

示例1:

protected IQueryable<Database.Product> GetActiveProducts( ObjectSet<Database.Product> products ) {

    var allowedStates = new string[] { "Active" , "Pending" };

    return (
        from product in products
        where allowedStates.Contains( product.State )
            && product.Hidden == "No"
        select product
    );

}



例2:

Example #2:

protected IQueryable<Database.Customer> GetActiveProducts( ObjectSet<Database.Customer> customers ) {

    var allowedStates = new string[] { "Active" , "Pending" };

    return (
        from customer in customers
        where allowedStates.Contains( customer.State )
            && customer.Hidden == "No"
        select customer
    );

}



如你所见,这些方法除了相同实体类型,他们操作的。我有10个以上这些类型的方法,一个是在我的系统中,每个类型的实体。

As you can see, these methods are identical apart from the Entity types they operate on. I have more than 10 of these types of methods, one for each type of Entity in my system.

我想知道我怎么能有这1单一方法我可以传递任何实体类型,并有如果2场/性能存在,执行where子句。

I am trying to understand how I could have 1 single method for which I could pass in any Entity type, and have it perform the where clause if the 2 fields/properties exist.

我不使用数据库中继承,所以就作为系统进入,这是巧合,每个实体类型都有一个领域的隐藏和国家。

I do not use Inheritance in the database, so as far as the system goes, it is coincidental that each of the Entity types have the fields "Hidden" and "State".

我的谷歌搜索告诉我它是与使用Expression.Call(),但我的头大楼代码现在纺!

My Googling tells me it has something to do with building code using Expression.Call() but my head is now spinning!

推荐答案

我想说添加接口是一个简单的选择比用表达式树的的反射搞乱。 EF实体分部类,所以你应该能够做这样的事情:

I'd say adding interfaces is a simpler option than messing with the expression tree or reflection. EF entities are partial classes, so you should be able to do something like:

更新以包括类约束(见标志的评论)

public interface IHideable
{
  string State { get; }
  string Hidden { get; }
}

...

namespace Database
{
  public partial class Product : IHideable { }
  public partial class Customer : IHideable { }
}

...

protected IQueryable<T> GetActive<T>(ObjectSet<T> entities)
    where T : class, IHideable
{
  var allowedStates = new string[] { "Active" , "Pending" };    

  return (    
    from obj in entities
    where allowedStates.Contains(obj.State)
        && obj.Hidden == "No"
    select obj
  );
}  

这篇关于LINQ的实体框架的通用滤波方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆