2013-10-04 3 views
1

친구 Linq에서 일하고 있어요. Entity Model과 함께 linq 쿼리에 join을 사용합니다.Linq 가입 C#

var Records = from Cats in Context.Categories 
join prod in Context.Products on Cats.Id equals prod.Category_Id 
select new { CatName = Cats.Name, ProdName = prod.Name }; 

나는 개체의 목록에서 레코드 var을 변환하려고하므로 entite 값 (제품, 범주)을 모두 보유하는 중간 개체를 만듭니다. 이제이 var을 다음과 같이 목록으로 캐스팅하면

List<test> testList = (List<test>)Records; 

을 Record.ToList(); 컴파일러 오류입니다. 내가 var 개체를 listview에 프론트 엔드에 바인딩하기 위해 목록에 캐스팅하는 방법. 거기에 람다의 대안도 인정 될 것입니다. 내 접근 방식이 맞습니까?

내 테스트 클래스는이다 : 조회에

class test{ 
string catname; 
string productname; 
} 
+0

이것은 결합 자체와는 관련이 없으며, 주조와 관련이 있습니다. 맞습니까? Btw, 오류가 발생하면 실제로 오류를 알려주는 것이 좋으므로 추측 할 필요가 없습니다. – walther

+1

'test' 유형 정의 란 무엇입니까? –

+0

테스트는 하나 이상의 열에서 레코드를 얻기 위해 카테고리 및 제품 필드를 보유하는 클래스입니다. –

답변

2

new Test를 만들고 그에 따라 속성을 설정하고 마지막으로 전화 (당신이 속성을 정의해야합니다) 다음과 같이 테스트 클래스를 정의 할 필요가 작동하도록하기 위해

var Records = (from Cats in Context.Categories 
       join prod in Context.Products on Cats.Id equals prod.Category_Id 
       select new test { CatName = Cats.Name, ProdName = prod.Name }).ToList(); 

ToList

List<test> testList = (from c in Context.Categories 
join p in Context.Products on c.Id equals p.Category_Id 
select new Test{ Category= c, Product= p}).ToList(); 

아래 클래스가있는 경우

public class Test{ 

    public string CatName{ get; set; } 
    public string ProductnName{ get; set; } 

} 

List<test> testList = (from c in Context.Categories 
join p in Context.Products on c.Id equals p.Category_Id 
select new Test{ CatName= c.Name, ProductnName= p.Name}).ToList(); 
+0

그 작업을 희망합니다. 찾고 오른쪽. 감사 –

3

사용 ToList(). 당신이

public class test { 
    public string catname {get;set;} 
    public string productname {get;set;} 
} 
+2

익명 객체는 여전히'test' 타입으로 캐스팅되지 않습니다. –

+0

어떻게 객체를 형 변환합니까? @ lazyberezovsky –

+1

@ lazyberezovsky 네, 맞습니다. 그것을 놓쳤습니다. 문제는 단지 '시험' – Jehof