LINQ的实体框架的通用滤波方法 [英] Linq Entity Framework generic filter method
问题描述
我有一些方法,从我的实体(使用实体框架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屋!