什么是此实体查询的通用实现

时间:2016-04-12 11:30:27

标签: c# asp.net asp.net-mvc

如何通用实现以下查询

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);

2 个答案:

答案 0 :(得分:0)

在不知道12100是否为硬编码的情况下,这可能是一个很好的起点:

更新以反映评论:

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);
}