2012-05-25 5 views
0

그리드를 채우는 쿼리가 있습니다. 다음은 쿼리입니다.LINQ 쿼리에서 값 가져 오기

var query = from r in DbContext.Groups 
      select 
      new 
       { 
       r.Id, r.Name, r.Description, r.UpdatedBy, r.UpdatedDate, 
       GroupType =DbContext.ProductTypes.Where(p=>p.Id == 
              r.ProductTypes_Id).Select(t=>t.Name) 
       }; 

그래서 다른 테이블에서 추출한 grouptype의 값이 값을 표시하지 않습니다. 형식 (System.Common ....)을 표시하고 있습니다. 이 문제를 해결하는 데 나를 도울 수 있니?

답변

1

어쩌면

GroupType =DbContext.ProductTypes.Where(p=>p.Id == r.ProductTypes_Id).Select(t=>new { name = t.Name})

또는

GroupType =DbContext.ProductTypes.Where(p=>p.Id == r.ProductTypes_Id).FirstOrDefault().Name

0

항목이 아닌 순서를 선택하고 있습니다.

GroupType =DbContext.ProductTypes.Where(p=>p.Id == 
          r.ProductTypes_Id).Select(t=>t.Name).Single() 

공지 끝에 .Single()의 추기 : 당신은 다시 하나 개의 값을받을거야 알고있는 경우 .Single 연산자를 사용합니다.

(이것은 단지 .Select 운영자 구현 클래스의 기본 .ToString() 방법을 나타내는 때문에이 유형의 이름을 보여주는 된 이유입니다.) 당신이를 반환하는

DbContext.ProductTypes.Where(p=>p.Id == r.ProductTypes_Id).Select(t=>t.Name)

을 기대하고있다

0

단일 값? 지금은 단일 값이 아닌 linq 익명 형식 목록을 지정하는 것처럼 보입니다.

단일 값을 원하면 반환 값을 준비하거나 준비하지 않으면 First 또는 FirstOrDefault를 사용하십시오.

0

.Select(t=>t.Name) 

의 결과는

IEnumerable<ProductType> 

그래서 당신이 아니라 콜렉션의 하나의 값을 가질 수 있습니다.

var query = from r in DbContext.Groups 
     select 
     new 
      { 
      r.Id, r.Name, r.Description, r.UpdatedBy, r.UpdatedDate, 
      GroupType =DbContext.ProductTypes.Single(p=>p.Id == 
             r.ProductTypes_Id).Name 
      }; 

그러나,이 코드는 위험한 일을 포함하고 제품 유형 인 경우 내가 (추가 검사를 추가하는 예를 들어,이 코드는 예외가 발생합니다 추천 할 것입니다 :

예를 들어,이에 쿼리를 변경 찾을 수 없음, 등등), 이상적으로이 코드를 저장소 또는 그와 유사한 것으로 이동하십시오.

0

이 왜 간단한 동작을

from r in DbContext.Groups join p in DbContext.ProductTypes on r.ProductTypes_Id equals p.Id 
select new { Id = r.Id, Name = r.Name, Description = r.Description, UpdatedBy = r.UpdatedBy, UpdatedDate = r.UpdatedDate, GroupType = p.Name }; 
을 조인을 사용하십시오