我希望能够从函数内的后续查询中提取条件语句。这是 EF 查询的 linq。我该怎么做?有没有其他方法可以应用面向对象的原则(如开放/封闭)?
var query = new UvwRequestAssignmentManagementBO().GetAll().Where(uvw => (uvw.FK_ProcessStep == 2)
&& (uvw.FK_Entity == SecurityContext.Current.User.FK_Entity)
&& (uvw.FK_Manager == 15))
.Select(p => new ReqSupAdminGridVm()
{
NameFamily = p.NameFamily,
RequestDate = p.RequestDate,
RequestNo = p.RequestNo,
RequestType = p.RequestType == 1 ?"a"
: (p.RequestType == 2 ? "b"
: (p.RequestType == 3 ? "c" :
(p.RequestType == 4 ? "d" : ""))),
RequestEvaluationStatus = p.RequestEvaluationStatus_Aggregation == 1 ? "a"
: (p.RequestEvaluationStatus_Aggregation == 2 ? "b"
: (p.RequestEvaluationStatus_Aggregation == 3 ?"c"
:(p.RequestEvaluationStatus_Aggregation == 4 ? "d" : ""))),
});
例如而不是写:
RequestType = p.RequestType == 1 ?"a"
: (p.RequestType == 2 ? "b"
: (p.RequestType == 3 ? "c" :
(p.RequestType == 4 ? "d" : ""))),
我希望能够在另一个类中编写它:
RequestType = ReqType.GetReqType(p.RequestType);
string GetReqType(int type){
switch(type){
case 1:
return "a";
case 2:
return "b";
}
}
最佳答案
查看 PredicateBuilder ,它可以让你做我想你想做的事,我自己在最近的一个项目中使用过它,代码可重用且可读。
我为我的模型创建了这样的谓词:
using System;
using System.Linq;
using System.Linq.Expressions;
namespace MyModels
{
using Predicate = Expression<Func<Component, bool>>;
public partial class Component
{
public static Predicate HasKeywordContaining(string keyword)
{
return c => c.Keywords.Any(k => k.Value.Contains(keyword));
}
public static Predicate IsOwnedBy(string ownerName)
{
return c => c.OwnerName.Contains(ownerName);
}
public static Predicate HasPartNoContaining(string partNo)
{
return c => c.PartNo.Contains(partNo);
}
}
}
然后我可以使用它们来构建这样的查询:
var whereComponent = PredicateBuilder.True<Component>();
whereComponent = whereComponent.And(Component.HasKeywordContaining(keyword));
whereComponent = whereComponent.And(Component.IsOwnedBy(ownerName));
var components = from c in db.Components.Where(whereComponent)
当然,这不涉及客户端过滤。
关于c# - 如何从linq查询中提取条件语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18712110/