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
Related
i am getting an error that says 'Non Static Method requires a target'
Here is the code that is causing me the error, could anyone possible shed some light on this?
//TODO: Error, Non static method requires a target.
var orderItem =
_context.PurchaseOrderItems.FirstOrDefault(
p => p.JobReference == item.JobReference && p.ItemNumber == item.ItemNumber);
return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
.Where(d => d.PurchaseOrderItem.Id == orderItem.Id)
.ToList();
The FirstOrDefault method may return null value if no query results returned there:
var orderItem = _context.PurchaseOrderItems.FirstOrDefault(
p => p.JobReference == item.JobReference && p.ItemNumber == item.ItemNumber);
Since orderItem.Id throws NullReferenceException when orderItem is null, it will propagate to LINQ throwing TargetException as mentioned in question (see this post and this post for more info).
Hence, you need to check presence of null value from orderItem by modifying second LINQ query to this one:
return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
.Where(d => (orderItem != null && d.PurchaseOrderItem.Id == orderItem.Id))
.ToList();
NB: Null checking must takes place before retrieving property Id of orderItem to prevent NullReferenceException.
As an alternative, if condition to check against null value may be used without modifying second query:
if (orderItem != null)
{
return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
.Where(d => d.PurchaseOrderItem.Id == orderItem.Id)
.ToList();
}
Change the FirstOrDefault to Single because in the next line you will get to its properties and you dont want a NullReferenceException
I have written this code
IQueryable<Site> sites = context.MainTable.Include("RelatedTable");
if (!string.IsNullOrEmpty(param1)) {
sites = sites.Where(s => s.RelatedTable != null && s.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
}
foreach (string secondaryPolicy in secondaryPolicies)
{
sites = sites.Where(s => s.RelatedTable != null && s.RelatedTable.Any(p => p.Name == secondaryPolicy.ToLower() && p.PolicyType == "secondary"));
}
return sites.ToList();
However at the ToList line I am getting the exception
Cannot compare elements of type
'System.Collections.Generic.ICollection`1[[Project1, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null]]'. Only primitive types,
enumeration types and entity types are supported.
You can't compare a related table to null directly. Instead, compare against your foreign key member (assuming that PrimaryTable reference RelatedTable using a member called RelatedTableId.
sites.Where(s => s.RelatedTableId != null && s.RelatedTable.Any(
p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
You may even be able to get away with removing the null check completely. Since this query is run against the database, you won't get a NullReferenceException and it may work. You'll have to double check on that though.
It is because that you have a null check in the where clause.
The error can occur if navigation collection compared with null. It should be checked if Any record exist. In the particular example Any is used anyway, so check collection to null is redundant
Incorrect
dbContext.MainTable.Where(c => c.RelatedTable==null )
Correct
dbContext.MainTable.Where(c => !c.RelatedTable.Any() )
Collection field can be null in this case you get exception NullReferenceException
when use RelatedTables.Any()
If you add RelatedTables != null as in a question then you can get
Cannot compare elements of type
'System.Collections.Generic.ICollection`1[[Project1, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null]]'. Only primitive types,
enumeration types and entity types are supported.
If you get the NullReferenceException exception, lazy loading is not turned off and you are good with lazy loading for the field then to prevent exception mark field with virtual keyword to allow lazy loading for the field
virtual ICollection<Table> RelatedTables{ get; set; }
I don't have a Foreign Key field configured because the relationship between MainTable and RelatedTable in my case is 1 to 1. However for a 1 to many relationship if you don't have foreign key but you have a navigation property to the MainTable model in the RelatedModel model the following solution also works.
1 to 1
var result = from s in context.Sites
join r in context.RelatedTable on s.Id equals r.Id
select s;
return result;
1 to many
var result = from s in context.Sites
join r in context.RelatedTable on s.Id equals r.Site.Id
into rs
where rs.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary")
select s
I also have the same situation. It then passed by comparing null with FirstOrDefault(). In your case, I applied as per below
sites = sites.Where(s => s.RelatedTable.FirstOrDefault() != null && s.RelatedTable.Any(p => p.Name == param1.ToLower() && p.PolicyType == "primary"));
It work me , I just remove the null check;
correct:
result=
db.EmpTable.FirstOrDefault().ProjectsAssign.Name,
InCorrect :
result=
db.EmpTable!=null && db.EmpTable.FirstOrDefault().ProjectsAssign!=null ?
db.EmpTable.FirstOrDefault().ProjectsAssign.Name : null,
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 getting this error when I try to retrieve some data. Here is how I am querying
using (_realtyContext = new realtydbEntities())
{
foreach (int yr in years)
{
var standard = (from feest in _realtyContext.FeeStandards
where feest.Year == yr && feest.FeeCategory.CategoryName == "PropertyFee"
select feest).SingleOrDefault();
var chargeItem = (from chrgItem in _realtyContext.PropertyFees
where chrgItem.FeeStandardID == standard.FeeStandardID
&& chrgItem.HousholdId == Householder.HouseholdID
select chrgItem).SingleOrDefault();
this._propertyFees.Add(chargeItem);
this._standards.Add(standard);
}
}
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
the error is on the 2nd query.(var chargeItem)
this query throw an error: var chargeItem =...
.SingleOrDefault() returns null when no records are found, and in the next statement you're using "standard" as if it is never null.
But that's just one of the many possible causes...
you have to check if standard is null. SingleOrDefault() will return null if there are no results
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.