In the datatable return one column list, in this scenario table return null value, I want to handle null values
DataTable PreviousQuarter = GroupFive.Tables["PreviousQuarter_108_49_100_51"];
LastQuarter.Merge(PreviousQuarter);
var AHCT = (from ah in PreviousQuarter.AsEnumerable()
where ah.Field<int>("ParameterID") == 10
|| ah.Field<int>("ParameterID") == 11
|| ah.Field<int>("ParameterID") == 12
|| ah.Field<int>("ParameterID") == 13
select ah.Field<int>("Tot_Tkts_Closed")).ToList();
if (AHCT == null)
{
Response = "";
}
It will come null , I am getting error Specified cast is not valid .
how to handle this error.
Your are selecting a value which is not available in table and before getting the result you type cast it into int.
That's why it throws error.
Its better to select first and then convert it into int.
I think #madreflection gave you the answer in the comments.
Since you're getting this error:
Specified cast is not valid
my guess is that you have a null value in the Tot_Tkts_Closed column. In that case, cast to nullable int int? instead. Update this line:
select ah.Field<int?>("Tot_Tkts_Closed")
The other possibility is ParameterID is null, in which case a similar change should resolve it: ah.Field<int?>("ParameterID").
Rather than checking if the list is null you could check to see if its empty. In that case, use the Count property:
if (AHCT.Count == 0)
{
Response = "";
}
Related
Considering the following code
IEnumerable<String> query = null;
query = from x in xml.Descendants(xmlMasterContainerName).Descendants(xmlElementName)
let guid = x.Attribute("guid") ?? new XAttribute("guid", "-1")
where x.Attribute(xmlAttributeIdName).Value == xmlAttributeIdValue
select guid.Value;
I get the 'object reference not set' when trying query.ToList()
This is very probably caused by 'select guid.Value' when 'x.Attribute(xmlAttributeIdName).Value == xmlAttributeIdValue' does not exist.
How can I check the where statement for existing value before selecting?
Thanks
In XLinq, you usually don't use Attribute().Value directly, because of the exact error you are getting. Instead, you cast it. The cast will result in null if Attribute() returned null, so there will be no exception.
So, you would change your where clause to this:
where ((string)x.Attribute(xmlAttributeIdName)) == xmlAttributeIdValue
and your select to this:
select (string)guid
BTW: I would write that code like this:
var query = xml.Descendants(xmlMasterContainerName)
.Descendants(xmlElementName)
.Where(x => ((string)x.Attribute(xmlAttributeIdName)) ==
xmlAttributeIdValue)
.Select(x => (string)x.Attribute("guid") ?? "-1");
If there is no attribute xmlAttributeIdName you will get an exception accessing Value property. Use casting instead (it will return default value). Also you don't need to create attribute - you can simply return value:
IEnumerable<String> query = null;
query = from x in xml.Descendants(xmlMasterContainerName)
.Descendants(xmlElementName)
where (string)x.Attribute(xmlAttributeIdName) == xmlAttributeIdValue
select (string)x.Attribute("guid") ?? "-1";
I am trying to perform left outer join on 2 objects and getting an error : Object reference not set to an instance of an object.
The objects look like that
var deliverables = OCHART.GetACAPValues(organization, ReportingPeriod, FiscalYear, "(09-10.10a) Outreach Significant").ToList();
var references = (from rf in OCHART.References where rf.RefType.Equals("09-10.10a") && rf.Comments.Equals("2") select rf).ToList();
In which deliverables might often return 0 records. Unfortunately I cannot just go and join two tables from database so deliverables must be an object.
Can somebody please point me in the right direction
Thanks,
My code is
var items = (from rf in references
join pt in deliverables on rf.Description equals pt.b into prt
from x in prt.Where(prt2 => prt2.a.Equals(audience)).DefaultIfEmpty()
where rf.RefType.Equals("09-10.10a") && rf.Comments.Equals("2")
select new
{
audience = (string)(audience == null ? "" : audience),
RefType = (string)(rf.RefType == null ? "" : rf.RefType),
RefOrder = (int)(rf.RefOrder == null ? 0 : rf.RefOrder),
refName = (string)(rf.Description == null ? "" : rf.Description),
collumn_attr = (string)(x.b == null ? string.Empty : x.b),
value = (int)(x.ACAP == null ? (int?)null : x.ACAP)
})
.OrderBy(o => o.RefOrder)
.Take(9)
.ToList();
EDIT:
After some more debuging it appears that I get error on following lines in my code
collumn_attr = (string)(x.b == null ? string.Empty : x.b),
value = (int)(x.ACAP == null ? (int?)null : x.ACAP)
I noticed even when I have values (added for testing) in deliverables and when values are matching the query will execute properly, but when there is no match in deliverable that's when I get the error message.
The issue is probably with handling the null values.
I think x is null and is causing a NullReferenceException in the following lines:
collumn_attr = (string)(x.b == null ? string.Empty : x.b),
value = (int)(x.ACAP == null ? (int?)null : x.ACAP)
This judgment is based on the from x in line's DefaultIfEmpty() call, typical of left-outer-joins.
In database code, you would write something like x.ACAP == null to detect the case where there was no matching join element. If you change this replace the 'x.property == null' checks with "x == null" checks, I suspect your problem will clear up.
There's still the problem with the second line - you're going to get an exception at run-time if you try to cast the value (int?)null to an integer. Using a meaningful default int value such as 0 in the case that x == null will clear that up.
If you step through your code, before the query is executed do you actually see "deliverables" and "references" being populated with data ?
Investigate all child tables/properties you're using in your query. The reason you're getting that error is most likely because one of the properties you're using while comparing is null.
.RefType .Comment for example.
Maybe .RefType is null and it's having problems sorting at the end. Difficult to say without seeing what's in those two collections.
Added after your comment:
Note that it's better not to use .Equals() when your variable could be null. Use == instead. Reference: http://www.dotnetperls.com/string-equals
Also imagine that (x.ACAP == null ? (int?)null : x.ACAP) returns a null.
You're casting that whole thing as an int : value = (int)(x.ACAP == null ? (int?)null : x.ACAP). Casting null as n int will obviously fail
Just for the record, the new Null-conditional operators in C# 6.0 could be used like this:
collumn_attr = x?.b ?? string.Empty,
value = x?.ACAP
select new
{
Selected = (cvf != null && cvf.Deleted==false)
}
The above statement proceeds to check cvf.Deleted even if cvf is null. Then it throws an invalid object reference error.
How do I fix this?
Probably something else going on since && will short-circuit evaluate. That said, try this instead:
select new
{
Selected = cvf != null
? !cvf.Deleted
: false
};
Anybody can tell why the ToList() throws an exception?
var duplicates =
from typeMappings in _liveTable.Where(r =>
(r.ProviderId == providerId) && (r.ExchangeId == exchangeId))
join dataDictionary in _liveDataSet.DataDictionary.Where(r =>
(r.DataDictionaryTypeId == dataDictionaryTypeId))
on typeMappings.DataDictionaryId equals dataDictionary.DataDictionaryId
select typeMappings.ConfigId;
if (duplicates.ToList().Count > 0)
{ ... }
The Exception message is:
'duplicates.ToList()' threw an exception of type 'System.Data.StrongTypingException' System.Collections.Generic.List {System.Data.StrongTypingException}
Thanks
From MSDN:
StrongTypingException
The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value.
So the problem occurs because one of the properties you access in the query is null. Check which properties of your DataTable are allowed to be null, and check it with a call to IsNull before you try to get the value.
Try to use that to eleminate Null value
var duplicates =
from typeMappings in _liveTable.Where(r =>
(r.ProviderId == providerId) && (r.ExchangeId == exchangeId))
join dataDictionary in _liveDataSet.DataDictionary.Where(r =>
(r.DataDictionaryTypeId == dataDictionaryTypeId))
on typeMappings.DataDictionaryId equals dataDictionary.DataDictionaryId
select new
{ ConfigId = typeMappings.ConfigId = null ? "anyValueyouwhant" : typeMappings.ConfigId};
juste to test without null value
I try to execute this Linq request :
var lqClassResult = from classItem in this.dataSet._class.AsEnumerable()
join namespaceItem in this.dataSet._namespace.AsEnumerable()
on classItem.Field<int>("namespace_id") equals namespaceItem.Field<int>("id")
where classItem.Field<string>("class_name").ToLowerInvariant().Contains(className.ToLowerInvariant()) &&
namespaceItem.Field<string("namespace_name").ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
orderby namespaceItem.Field<string>("namespace_name"),classItem.Field<string>("class_name")
select new {
class_name = classItem.Field<string>("class_name"),
namespace_name = namespaceItem.Field<string>("namespace_name")
};
But when i execute it, Visual Studio Throw a NullReferenceException because of this line :
namespaceItem.Field("namespace_name").ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
in where clause.
If anyone can help me it would be great
Try
on classItem.Field<int>("namespace_id") equals namespaceItem.Field<int>("id")
let namespaceName = namespaceItem.Field<string("namespace_name")
where classItem.Field<string>("class_name").ToLowerInvariant().Contains(className.ToLowerInvariant()) && namespace != null &&
namespace.ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
I would guess that namespaceItem.Field("namespace_name") is returning null.
Is this a valid return value for that method? If not, then check your underlying code.
If this is a valid return value then you need to check for a null before calling ToLowerInvariant():
var lqClassResult = from classItem in this.dataSet._class.AsEnumerable()
join namespaceItem in this.dataSet._namespace.AsEnumerable()
on classItem.Field<int>("namespace_id") equals namespaceItem.Field<int>("id")
where classItem.Field<string>("class_name").ToLowerInvariant().Contains(className.ToLowerInvariant()) &&
namespaceItem.Field<string("namespace_name") ! = null &&
namespaceItem.Field<string("namespace_name").ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
orderby namespaceItem.Field<string>("namespace_name"),classItem.Field<string>("class_name")
select new {
class_name = classItem.Field<string>("class_name"),
namespace_name = namespaceItem.Field<string>("namespace_name")
};
Note the extra null check:
namespaceItem.Field<string("namespace_name") ! = null &&
However, this is only a guess: you need to determine where the null value is coming from.
2 possibilities:
There is no field
Field("namespace_name")
returns null because there is no field-
There isa field, but
Field("namespace_name").ToLowerInvariant().
returns null because the VALUE in namespace_name is a null so ToLowerInvariant also returns null, which will blow the contains.