Fan*_*rns 3 c# linq-to-entities entity-framework
我有一些方法对我的实体的数据执行标准过滤(使用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
);
}
Run Code Online (Sandbox Code Playgroud)
示例#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
);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,这些方法与它们运行的实体类型完全相同.我有超过10种这样的方法,一种用于我系统中的每种类型的实体.
我试图理解我如何能够在任何实体类型中传递1个单一方法,并且如果存在2个字段/属性,则让它执行where子句.
我不在数据库中使用继承,因此就系统而言,每个实体类型都有"隐藏"和"状态"字段是巧合.
我的谷歌搜索告诉我它与使用Expression.Call()构建代码有关,但我的头现在正在旋转!
我想说添加接口比弄乱表达式树或反射更简单.EF实体是部分类,因此您应该能够执行以下操作:
更新为包含类约束(请参阅Mark的注释)
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
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3980 次 |
| 最近记录: |