如何通用实现以下查询
double sum=context.Employees.Where(e=>(e.Id==12 && e.Sl==100)).Sum(e=>e.Salary);
我正在使用存储库系统。 我想要这样的东西
T total=GetTotalSalary((e.Id==12 && e.Sl==100),e.Salary);
答案 0 :(得分:0)
在不知道12
和100
是否为硬编码的情况下,这可能是一个很好的起点:
更新以反映评论:
public abstract class Contract
{
public decimal Salery { get; set; }
}
public class EmployeePermanent : Contract {
}
public class Employee : Contract
{
public int Id { get; set; }
public int Sl { get; set; }
public void Test()
{
new List<Employee>().AsQueryable().GetTotalSalary(x => x.Id == 12 && x.Sl == 100);
}
}
public static class QueryExtensions
{
public static decimal GetTotalSalary<T>(this IQueryable<T> queryable, Expression<Func<T, bool>> expression) where T : Contract
{
return queryable.Where(expression).Sum(arg => arg.Salery);
}
}
答案 1 :(得分:0)
只需将变量作为参数传递给函数,并在linq中使用它们
this.setvalueToExpression("#{bindings.Orderno.inputValue}",
"sample");//pass string value
public void setvalueToExpression(String el, Object val) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory expressionFactory =
facesContext.getApplication().getExpressionFactory();
ValueExpression exp =
expressionFactory.createValueExpression(elContext, el,
Object.class);
exp.setValue(elContext, val);
}