У меня есть запрос LINQ to SQL, который создает объект типа {System.Data.Linq.DataQuery}.Моя проблема в том, что я получаю исключение при попытке определить, является ли список пустым (или нулевым).
Я пробовал различные тесты и искал ответ в StackOverflow, но ничего из того, что я пробовал, не поможет мне пройти через этоисключение:
// 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, проверяя на null (если carrierCodes! = null), но каждый раз оценивается как false.Я пытался получить количество экземпляров различными способами, но поскольку список пуст, это дает мне исключение при попытке проверить счет.
Что сбивает с толку, так это то, что список carrierCode не равен нулю, но даетСсылка на исключение объекта Null.
PS Это исключение:
"Object reference not set to an instance of an object."
Спасибо,
Запутался в Сиэтле.
ОБНОВЛЕНИЕ
Я попробовал следующие предложения - все они выдают то же исключение, что и раньше.Я приложил диалог исключения и детали исключения:
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](https://i.stack.imgur.com/fG8wr.png)
Обновленный код:
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;
Ответ: проблема была в моем профиле Идентификатор был нулевым..Any () - хорошая замена для Count () == 0 btw