SELECT NEW with potentially null field using LINQ and Entity Framework

I want to quickly select some lines, format them well for the / selectlist dropdown, or something like that, but I have a field in db that is null (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 LINQ in this case?

Edit:

I did not pay attention to the fact that since it uses an entity structure, methods that work with standard LINQ cannot be used if they do not have SQL translation.

  • DateOfBirth is a Nullable <DateTime>
  • Source is Entity Framework 4
+4
source share
4 answers

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

Sort of:

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

Often, nullable can be handled with variable ?? default variable ?? default

 var res = nullableVariable ?? defaultValue; 

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

+2
source

Since you are just adding rows, try this.

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

In VB.NET

 Dim athletes = (From at In _db.Athletes Select New With{ .Name = at.Name + " " + If(at.Field(Of Object)("DateOfBirth") = Nothing, string.Empty, at.Field(Of Object)("DateOfBirth")), .Id = at.AthleteId }).ToList() 
0
source

Source: https://habr.com/ru/post/1338872/


All Articles