2009-09-21 3 views
1

linq 쿼리를 사용하여 일부 외래 키 데이터를 미리 가져 오려고합니다. 내 문제를 설명하는 빠른 예는 다음과 같습니다LINQ : 두 번째 테이블에서 데이터 프리 패치

var results = (from c in _customers 
       from ct in _customerTypes 
       where c.TypeId == ct.TypeId 
       select new Customer 
          { 
          CustomerId = c.CustomerId, 
          Name = c.Name, 
          TypeId = c.TypeId, 
          TypeName = ct.TypeName, <-- Trying to Prefetch this 
          }).ToList(); 

고객 클래스는 다음과 같습니다

[Table(Name = "Customers")] 
public class Customer 
{ 
    [Column(Name = "CustomerId", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] 
    public int CustomerId { get; set; } 

    [Column(Name = "Name")] 
    public string Name { get; set; } 

    [Column(Name = "TypeId")] 
    public int TypeId { get; set;} 

    public string TypeName { get; set; } 

    public Confession(){} 
} 

그러나 LINQ는이 엔티티 타입 '고객'을 명시 적으로 건설 "과 NotSupportedException이 던지는 않는 못하게 쿼리가 허용되지 않습니다. "

분명히 잘못 접근하고 있습니다. 올바른 방향의 포인터가 가장 도움이 될 것입니다.

답변

1

이렇게 고객을 구성 할 수 없습니다.

당신이 필요로하는 속성을 캡슐화하는 새로운 클래스를 만드는 것이 가장 쉬운 방법입니다. 이처럼 수행하여 고객 클래스의 모든 것을 얻을 수 있습니다

var results = (from c in _customers 
       from ct in _customerTypes 
       where c.TypeId == ct.TypeId 
       select new 
         { 
         Customer = c, 
         TypeName = ct.TypeName 
         }).ToList(); 
0

정품 사전로드를 수행 할 경우, 다음을 수행 할 수 이것은이 Customer 간의 조인 거기에 가정 (

을 및 CustomerType 데이터베이스의 테이블 및 SQL에 그 LINQ는 그것에 대해 알고있다.) 그런 다음 이렇게 TypeName에 액세스 할 수

MyDataContext dc = new MyDataContext(); // Use your application-specific DataContext class 
DataLoadOptions loadOptions = new DataLoadOptions(); 
loadOptions.LoadWith<Customer>(c => c.CustomerType); 
dc.LoadOptions = loadOptions; 
var results = from c in dc.GetTable<Customer>() select c; 

(c은에 Customer입니다) :

c.CustomerType.TypeName; 
관련 문제