{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
}
예외 :
업데이트 코드 :
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
이 쿼리에 의해 반환되지 않으면
'shipTEntity'는 어떻게 미리로드되어 있습니까? 'CompanyProfile'과'CargoControlNum'이 null이 아니라고 확신합니까? – Reddog
나는 지금 null이되는 두 개의 매개 변수를 확인합니다. 고맙습니다. – nocarrier
또는 context.CompanyProfiles 중 하나가 null 일 수 있습니까? 어떤 속성 (예 : cc.ProfileTypeID)에 액세스하려고하면 예외가 발생합니다. –