데이터베이스에서 얻은 정수를 사용하여 Linq를 사용하여 데이터베이스에서 일부 데이터 검색

절대로 필요한 것

나는 int 유형의 CompanyId를 검색하고 LINQ를 사용하여 데이터베이스에서 더 많은 데이터를 검색하려는 Asp.Net MVC 응용 프로그램에서 작업하고 있으며 다음 코드를 사용하여 수행합니다.

var companyId = db.UserProfiles.Where(u => u.UserName == User.Identity.Name)
                               .Select(u => u.CompanyId);
return db.CCUserHorizontals.Where(ccu=>companyId.Equals(ccu.CPId));

companyIdUserProfile에서 검색 하여 비교하는 데 사용했습니다.CPID

하지만 페이지를로드 할 때 다음과 같은 오류가 발생했습니다.

<m:message>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
</m:message>
<m:type>System.InvalidOperationException</m:type>
<m:stacktrace/>
<m:internalexception>
<m:message>
Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
</m:message>
<m:type>System.NotSupportedException</m:type>

이것에 대한 해결책을 알 수 있습니까?

하비브

첫 번째 쿼리는를 반환합니다 IQueryable<int>. 이는 정수 값의 모음입니다 (하나 / 단일 값만 포함 할 수 있음) . 나중에 쿼리에서 사용하려고 시도하고 오류가 발생합니다.

코드는 다음과 같아야합니다.

var companyId = db.UserProfiles.Where(u => u.UserName == User.Identity.Name)
                               .Select(u => u.CompanyId)
                               .FirstOrDefault();
return db.CCUserHorizontals.Where(ccu => ccu.CPId == companyId);

몇 가지 참고할 사항 :

  • 술어도 취 하므로 FirstOrDefault대신 사용할 수 있습니다.WhereFirstOrDefault

처럼:

var item = db.UserProfiles.FirstOrDefault(u => u.UserName == User.Identity.Name);
int companyId = 0;
if(item != null) companyId = item.CompanyId;
  • 당신은 / 수도 (또는하지 않을 수 있습니다) 전화 ToList쿼리를 구체화 반환 값에. 당신이 경우 DataContext방법에 배치됩니다 당신은 호출자의 방법의 결과를 액세스 할 경우에 예외를 얻을 것이다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관