使用EF扩展Select ....以容纳更多字段作为扩展名

时间:2016-06-16 04:40:51

标签: linq linq-to-entities entity-framework-6 projection

我有一个班级:

public class Employee
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int Salary { get; set; }

  public string Address {get;set;}
}

使用Entity Framework进行查询是:

var selectedEmployee = entities.Employees
                             .Where(e=>e.Salary>10000)
                             .Select(emp => new EmpDTO
                                  {
                                      Id = emp.Id,
                                      Name = emp.Name,
                                      Salary = emp.Salary
                                  });

我的问题是: 我想允许扩展此查询而不重写基本查询。它应该允许通过扩展上面的查询在.Select(.....)中添加一个新字段。

不重写完整的查询:

var selectedEmployee = entities.Employees
                                 .Where(e=>e.Salary>10000)
                                 .Select(emp => new EmpDTO
                                      {
                                          Id = emp.Id,
                                          Name = emp.Name,
                                          Salary = emp.Salary,

                                          Address = emp.Address

                                      });

我该怎么做?

由于

1 个答案:

答案 0 :(得分:1)

如果我理解,你可以试试这个:

A

<强>实施

public IQuerable<EmpDTO> GetEmployee(Func<Employee, EmpDTO> projection = null)
{
    if(projection == null)
        projection = emp => new EmpDTO {
                                  Id = emp.Id,
                                  Name = emp.Name,
                                  Salary = emp.Salary,    
                                };
    return entities.Employees.Where(e => e.Salary > 10000).Select(projection);
}
  

如果您想要获得一些字段,例如var query = classInstance.GetEmployee(); //or query = classInstance.GetEmployee(emp => new EmpDTO { Id = emp.Id, Name = emp.Name, Salary = emp.Salary, Address = emp.Address }); Id和   Name有时需要额外的字段(并仅指定其字段)   作为方法参数),您应该只从DB获取所有字段   然后过滤它们取决于你的条件 - 这是不好的做法    SELECT * ,因此您应该获取默认字段集或指定所有所需字段mannualy。

使用SELECT *的解决方案:

Salary
  

在这种情况下,返回值为public List<EmpDTO> GetEmployee(Func<Employee, EmpDTO> projection) { var query = entities.Employees.Where(e => e.Salary > 10000).ToList().Select(x => { var item = projection == null ? new EmpDTO() : projection(x); item.Id = x.Id; item.Name = x.Name; item.Salary = x.Salary; return item; }).ToList(); } 而非List<T>;

<强>实施

IQuerable<T>