LINQ to Dataset DBNULL problem / null reference exception - c#

I have the following LINQ query which always results in an error when my "Remark" column in dtblDetail is null, even though I test if it is NULL.
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d.IsRemarkNull() ? null : d.Remark
};
The error message was:
"The value for column 'Remark' in table 'dtblDetails' is DBNull."
After adding the test for d.IsRemarkNull() a null reference exception is thrown.
Can you help me with this?
I've already checked the following websites but didn't find anything useful other than that I have to test for DBNULL. But as said this doesn't solve my problem.
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/3d124f45-62ec-4006-a5b1-ddbb578c4e4d
http://blogs.msdn.com/adonet/archive/2007/02/13/nulls-linq-to-datasets-part-3.aspx
http://www.vbforums.com/showthread.php?t=506645

The problem was that the whole 'd' item was empty.
So calling 'd.IsRemarkNull()' resulted in the null reference exception.
The following code fixed the problem:
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d == null? null : (d.IsRemarkNull() ? null : d.Remark)
};

Where is the error coming from? Is it possible that it is the d.IsRemarkNull() that is causing it? What does that method look like?
Perhaps:
DBNull.Value.Equals(d.Remark)

maybe this field doesn't allow null in db, get a default value for it, and avoid handling null values

Related

C# Where int isn't null in LINQ

I'm using C# in Visual Studio and I have a table with an attribute set to allow nulls, I try to get a query excluding null values like so:
var playerQueryDel = (from p in DB.Jugadores
where p.goles != null
orderby p.goles
select new
{
tiros = p.tirosPorteria,
goles = p.goles,
nombre = p.nombreJugador
}
).ToList();
Where goles is an attribute of type int that accepts nulls and I know that there are some records in the database with null values in this attribute, the problem is that is returns "empty" values, for example trying this:
System.Diagnostics.Debug.WriteLine($"Testing: {playerQueryDel[0]}");
Prints this:
Testing:
I also try to print to know if it is emptry like so:
System.Diagnostics.Debug.WriteLine($"{playerQueryDel[0] == null}");
Prints false, what is the cause of this "not null but empty" value and is there a way to check without having to parse it to something else?
I'll upload more information if needed :)
A couple of things to try: Check that the list contains any items. Check the individual field in the result being returned.
System.Diagnostics.Debug.WriteLine($"Testing: {playerQueryDel.Count}");
System.Diagnostics.Debug.WriteLine($"Testing: {playerQueryDel[0].goles}");

Linq Xelement and Class

So, let me explain my trouble.
I get a project which was develop by another guy, and he leaved the firm. Now i have to update the program but something going wrong when i import the solution.
Let see the code:
ListeDeTypeDePoste = (from e in xml.Descendants("profil")
select new TypeDePoste()
{
Nom = e.Element("name").Value,
Chaines = (from c in e.Elements("Chaine")
select new Chaine()
{
Code = c.Element("Code")?.Value,
Type = c.Element("Type")?.Value,
Nom = c.Element("Nom")?.Value,
OU = c.Element("OU")?.Value
}).ToList()
}).ToList<TypeDePoste>();
The trouble is on the .?Value for each properties in a Chaine Class, when i debug i can even debug the solution and if i remove them i got a NullReferenceException. With this code the previous realese .exe worked like a charm
You can use the operator ?. only in C# 6.0.
This is null-propagation operator. If you don't want to use it, you can change your assignment to properties of Chaine class:
select new Chaine()
{
Code = (c.Element("Code") == null) ? null : c.Element("Code").Value,
Type = (c.Element("Type") == null) ? null : c.Element("Type").Value,
Nom = (c.Element("Nom") == null) ? null : c.Element("Nom").Value,
OU = (c.Element("OU") == null) ? null : c.Element("OU").Value
}).ToList()
If you delete ? in this operator the assignment will crash because you try to get value of null.
If c.Element("Code") is null then this code will simply assign null to Code:
Code = c.Element("Code")?.Value;
But without ?:
Code = c.Element("Code").Value; //app will throw an exception because c.Element("Code") is null
This is because the Element calls in that code are sometimes returning null, because an element with the given name doesn't exist at that location in the XML document you're processing.
The ?. (null-conditional) operator tests for this, returning null in such a scenario.
If you use . instead (without adding your own null check), then a NullReferenceException will be thrown in such a scenario. This is by-design in C#.
The null-conditional operator was introduced in C# 6, so to use it you'll need to install Visual Studio 2015.

List.FindAll() shows error for null column values

objLst = objLst.FindAll(c => c.Emp_cod.Equals(string.Empty)
|| c.Emp_cod.Equals(null))
I am having a List of All Employees and New Employees who have been offered has emp_cod value null.
Now when i am trying to find New Employees using the above code it gives object reference error.
Emp_cod column is string defined as below when imported from SQL to DBML:
[Column(Storage = "_Emp_cod", DbType = "VarChar(10)")]
public string Emp_cod { get; set; }
You can try:
objLst = objLst.Where(c => String.IsNullOrEmpty(c.Emp_cod));
The reason you are getting the error is because you are trying to call instance method Equals on null object. You need to check for null first and then check for string empty.
objLst = objLst.FindAll(c => c.Emp_cod != null && c.Emp_cod.Equals(string.Empty));
Or better if you may use string.IsNullOrEmpty like Adrian's answer.
You may also try string.IsNullOrWhiteSpace if you want to check against, null, empty and white spaces, but only if you are using .Net 4.0 or higher
objLst = objLst.FindAll(c => string.IsNullOrWhiteSpace(c.Emp_code))

Null Linq Values

I cant get this to work. The State field is empty on certain occassions, I am trying to get the result to return "--" if it is empty, or doesn't exist.
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select new BondData()
{
CUSIP = c.Element("CUSIP").Value,
Description = (string)c.Element("ISSUER").Value,
Maturity= c.Element("MATURITYDT").Value,
AskYield = float.Parse(c.Element("ASKYIELD").Value),
State = (string)c.Element("STATE").Value ?? "--"
}
;
This just doesn't want to work. The error I am getting is:
NullReferenceException was unhandled. {"Object reference not set to an instance of an object."}
I KNOW that it does not exist. I thought that putting ?? "--" will return "--" if c.Element("STATE").Value is null.
I can resort to modifying the statement to:
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select c;
foreach(var t in CusipFields)
{
switch(t.name)
{
}
}
But I think that it is slower. And its not what I want.
Use this:
State = (string)c.Element("STATE") ?? "--"
instead of
State = (string)c.Element("STATE").Value ?? "--"
My answer assumes, that your problem is, that the STATE element is missing, not empty. Please tell me, whether or not that fixed your problem.
I think it's because c.Element("STATE") is null, not it's Value property.
try:
(string)c.Element("STATE") != null? (string)c.Element("STATE").Value : "--";
You're getting this error not because the Value property is null, but because c.Element(...) is null. You'll need to check for nulls in all of your Element() calls and take appropriate action in order to avoid this error.

If null.Equals(null) why do I get a NullReferenceException

I have the following line of code:
var selectedDomainID = lkuDomainType.EditValue.Equals(null)
? string.Empty
: lkuDomainType.EditValue;
Sometimes this generates a NullReferenceException. What I don't understand is why. Isn't the whole point of my code to check for null and if so assign string.empty? When I check in DEBUG it is stating that EditValue == null so what am I missing?
Use lkuDomainType.EditValue == null, otherwise you are trying to call an instance method on a null object. But the better option might be lkuDomainType.EditValue ?? String.Empty. Also watch out for lkuDomainType being null, unless it is a class not an object.
When you use Object.Property and Object is undefined, you are dereferencing a null pointer and that's why you get the exception. Instead, use:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If EditValue is null then you can't call Equals. In this cas you would have to do:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
Or you can simplify it by doing:
var selectedDomainID = lkuDomainType.EditValue ?? string.Empty;
you are trying to call the Equals method on a null object - do it like this instead:
lkuDomainType.EditValue == null
The problem is that you are using the object before checking if it's null. You are calling the Equals method of the object, which fails if the reference is null.
You have to exchange your lkuDomainType.EditValue.Equals(null) for lkuDomainType.EditValue == null.
EditValue == null. That means that there is no object there. You cannot call functions on null objects, even if the function is .Equals().
You're better off just saying "(lkuDomainType.EditValue == null)" in this case.
You should use String.IsNullOrEmpty here. Like this:
var selectedDomainID = String.IsNullOrEmpty(lkuDomainType.EditValue) ? string.Empty : lkuDomainType.EditValue;
Equals is a method, you're trying to call a method on a null object which is throwing an exception.
when EditValue is null you cannot call the Equals method on it so the best way to check is to use
lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If lkuDomainType.EditValue is null, then "lkuDomainType.EditValue.Equals(someObject)" is the same as coding "null.Equals(someObject)". Well, obviously "null" doesn't have any members or methods (it wouldn't be null if it did). That's why you get a NullReferenceException.
Most of the examples from the other posts will work, including String.IsNullOrEmpty, which is a method that returns a boolean value.
All current answers fail to address a critical point: the difference between calling Equals on a Nullable type (which is a struct) vs. class type.
Calling Equals on a Nullable typed object whose value is null will not issue an exception, while doing the same on a class typed object will.
Consider the following code:
int? num = null; // int? is Nullable<int>
String s = null; // String is a class
var equalsNullable = num.Equals(null); // works
var equalsClass = s.Equals(null); // throws
The reason is that Nullable's HasValue method is called in such case, see Jon Skeet's answer for more info.
As other people said, the way to go in the OP's case is to use == or ??.

Categories

Resources