Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT NEW with a potentially null field using LINQ and Entity Framework

Tags:

c#

linq

I want to quickly select some rows, format it nicely for a dropdownlist/selectlist or something like that - but I have a field in the db, that is nullable (DateOfBirth).

var athletes = (from at in _db.Athletes
           select new{
                  Name = at.Name + " " + at.DateOfBirth, 
                  Id = at.AthleteId 
                  }).ToList();

Is there a way to handle nullable types inside the LINQ in a case like this?

Edit:

I was not paying attention to the fact, that since this is using entity framework, methods that work with standard LINQ cannot be used unless they have a SQL translation.

  • DateOfBirth is a Nullable < DateTime >
  • Source is Entity Framework 4
like image 732
Kjensen Avatar asked Feb 08 '11 15:02

Kjensen


People also ask

Can Linq select return null?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer. Show activity on this post.

Is null in Linq C#?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.

Can single return null?

SingleOrDefault() will return null (or default of the type) if nothing exists but will throw exception if you have more than one match.


3 Answers

You can use the null coalesce operator, see Equivalent of SQL ISNULL in LINQ?.

Something like:

var athletes = (from at in _db.Athletes
           select new{
                  Name = at.Name + " " + (at.DateOfBirth ?? ""), 
                  Id = at.AthleteId 
                  }).ToList();
like image 59
Shan Plourde Avatar answered Nov 01 '22 05:11

Shan Plourde


Often a nullable can be handled using variable ?? default

var res = nullableVariable ?? defaultValue;

But be carefull with datetime, linq will try to implement this in SQL and DateTime.MinValue from C# is not within the valid range for SQL and will give you an error message.

like image 26
David Mårtensson Avatar answered Nov 01 '22 04:11

David Mårtensson


Since you are just doing string appending try this.

var athletes = (from at in _db.Athletes
           select new{
                  Name = at.Name + " " + (at.DateOfBirth ?? string.Empty), 
                  Id = at.AthleteId 
                  }).ToList();
like image 22
Steve Danner Avatar answered Nov 01 '22 03:11

Steve Danner