2016-06-16 2 views
0

를 사용하여 확장으로 더 많은 필드를 수용 할 수 있도록 : 엔티티 프레임 워크를 사용하여가 .... 내가 클래스가 EF

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

    public string Address {get;set;} 
} 

그리고 쿼리 것은 :

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

내 질문은 : I 기본 쿼리를 다시 작성하지 않고이 쿼리를 확장 할 수 있습니다. 위의 쿼리를 확장하여 .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

, 당신이 시도 할 수 있습니다 :

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, NameSalary 때로는 추가 필드를 사용하고 (경우에 따라 메서드 매개 변수로만 지정) DB에서 모든 필드를 가져와 필터를 조건에 따라 필터링해야합니다. SELECT *을 수행하는 것이 좋습니다. 기본 필드 집합을 가져 오거나 모두 원하는 필드를 수동으로 지정해야합니다. SELECT *와

해결책 :

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>이고;

구현 :

var items = classInstance.GetEmployee(emp => new EmpDTO { Address = emp.Address }); 
//items also will contain fields: Id, Name and Salary by default 
+0

가 전체 선택 재 작성하지 않고 주소를 추가 할 수 있습니까? 쿼리 = classInstance.GetEmployee (EMP => 새로운 EmpDTO { 식 emp.Id, 이름 = emp.Name, 급여 = emp.Salary, 주소 = emp.Address }); – Satyajit

+0

예, 프로젝션이 가변적 인 첫 번째 변형입니다. –