2012-01-24 3 views
1

{System.Data.Linq.DataQuery} 형식의 개체를 생성하는 LINQ to SQL 쿼리가 있습니다. 내 문제는 목록이 비어 있는지 확인하려고 할 때 예외가 발생하거나 null입니다. 당신이 볼 수 있듯이Linq.DataQuery 컬렉션에서 예외가 발생하고 있습니다. null 값을 확인할 수 없습니까?

// I try to declare explicitly: 
    IQueryable<DataAccess.Entities.CompanyProfile> carrierCodes = null; 


    // and implicitly 
     var carrierCodes = from cc in context.CompanyProfiles 
          where cc.ProfileTypeID == 9 && 
           cc.CompanyProfileCode == shipTEntity.CargoControlNum.Substring(0, 3) && 
           cc.CompanyProfileID == shipTEntity.CompanyProfile.CompanyProfileID 
          select cc; 



     // VAROIUS NULL REF TESTS 
     var _info = carrierCodes.FirstOrDefault(u => u != null); // fails 

     int itemCount = Enumerable.Cast<string>(carrierCodes.DefaultIfEmpty()).Count(); // fails 

     var InstanceCount = carrierCodes.Count(i => i != null); // fails 

     foreach (var companyProfile in carrierCodes) // fails 
     { 
      if (companyProfile != null) 
       itemCount++; 
     } 

     var exists = carrierCodes.DefaultIfEmpty().ToList(); // fails 

     int count = exists.Count; 

     return count > 0; 

, 내가 널 위해 테스트 FirstOrDefault 시도 (carrierCodes 경우 :

나는 여러 다른 테스트를 시도하고, 답변을 StackOverflow의를 통해 검색하지만 아무것도 나는이 예외 과거의 저를 얻을 것이다 시도하지 ! = null)하지만 매번 false로 평가됩니다. 인스턴스 카운트를 여러 가지 방법으로 얻으려고했지만 목록이 null이어서 카운트를 테스트 할 때 예외가 발생합니다.

carrierCode 목록이 null이 아니지만 Object Null 참조 예외를 제공한다는 점이 혼란 스럽습니다. ,

"Object reference not set to an instance of an object." 

감사합니다

시애틀의 혼란

:

PS이는 예외입니다. 나는 다음과 같은 제안을 시도했습니다

UPDATE는 - 그들은 모두 이전과 같은 예외를 생산하고 있습니다. 나는 예외 대화 및 예외 세부 사항을 첨부했습니다 :

var carrierCodes = from cc in context.CompanyProfiles 
          where cc.ProfileTypeID == 9 && 
           cc.CompanyProfileCode == shipTEntity.CargoControlNum.Substring(0, 3) && 
           cc.CompanyProfileID == shipTEntity.CompanyProfile.CompanyProfileID 
          select cc; 

     // the below all throw ex: 
     var isValid = carrierCodes.Count() == 0; 
     var isNull = carrierCodes.FirstOrDefault() == null; 

     if (carrierCodes.ToList().Count == 0) 
     { 
      //Don't try to access members of carrierCodes 
     } 

예외 :

My Exception

업데이트 코드 :

 var code  = shipTEntity.CargoControlNum.Substring(0, 3); 
     var profileId = shipTEntity.CompanyProfile.CompanyProfileID; 

     var profiles = from cc in context.CompanyProfiles 
         where cc.ProfileTypeID == 9 
         select cc; 

     var codesInProfiles = from p in profiles 
           where p.CompanyProfileCode == code 
           select p; 

     var carrierCodes = from c in codesInProfiles 
         where c.CompanyProfileID == profileId 
         select c; 

     //var carrierCodes = from cc in context.CompanyProfiles 
     //     where cc.ProfileTypeID == 9 && 
     //       cc.CompanyProfileCode == shipTEntity.CargoControlNum.Substring(0, 3) && 
     //       cc.CompanyProfileID == shipTEntity.CompanyProfile.CompanyProfileID 
     //     select cc; 

     if (!profiles.Any()) 
      return false; 

     if (!codesInProfiles.Any()) 
      return false; 

     if (!carrierCodes.Any()) 
      return false; 

답변 : 문제가 내 프로필 아이디가 null이었다. .ANY()는 더 CompanyProfiles이 쿼리에 의해 반환되지 않으면

+1

'shipTEntity'는 어떻게 미리로드되어 있습니까? 'CompanyProfile'과'CargoControlNum'이 null이 아니라고 확신합니까? – Reddog

+0

나는 지금 null이되는 두 개의 매개 변수를 확인합니다. 고맙습니다. – nocarrier

+0

또는 context.CompanyProfiles 중 하나가 null 일 수 있습니까? 어떤 속성 (예 : cc.ProfileTypeID)에 액세스하려고하면 예외가 발생합니다. –

답변

1

원래 본인의 의견에 따르면 shipTEntity에 사용 된 관련 엔티티 중 하나는 미리로드되지 않았을 것입니다. 아마도 그것은 CompanyProfile 일 것입니다.

이 문제를 해결하려면 데이터 컨텍스트에서 shipTEntity을 검색 할 때 컨텍스트에서 일부 DataLoadOptions.LoadsWith을 설정하여 관련 엔터티가 컨텍스트에서도로드되는지 확인해야합니다.

0

true해야 다음 BTW 카운트() == 0을위한 좋은 대용품이다

carrierCodes.Count() == 0; 

그리고

carrierCodes.FirstOrDefault() == null; 

으로 carrierCodes이 비어 있는지 확인하거나 nullpredicate 논증 Count()FirstOrDefault()이 필요하지 않습니다.

+0

이 경우에도 동일한 예외가 발생합니다. – nocarrier

0

이 시도 :

var carrierCodes = from cc in context.CompanyProfiles 
         where cc.ProfileTypeID == 9 && 
          cc.CompanyProfileCode == shipTEntity.CargoControlNum.Substring(0, 3) && 
          cc.CompanyProfileID == shipTEntity.CompanyProfile.CompanyProfileID 
         select cc; 

if (carrierCodes == null) { 
    return false; // or whatever 
} 

을 나는 carrierCodes 자체가 null 때문에 예외를 받고 생각, 그래서 당신이 그것에 작업을 수행하려고 할 때 (FirstOrDefault, 카운트), 사람들은에 수행하려고하는 null 객체

관련 문제