Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6068511
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T09:43:22+00:00 2026-05-23T09:43:22+00:00

I am having a problem returning a default DateTime value from a complex Linq-to-Sql

  • 0

I am having a problem returning a default DateTime value from a complex Linq-to-Sql query.

Hopefully the following simplified example shows the problem (although I haven’t run this exact code):

users.Select(u =>
  new MyDomainObject(
     u.Id,
     u.Transactions
        .Where(t => false) // empty results set
        .Select(t => t.TransactionTime) // TransactionTime is DATETIME NOT NULL
        .OrderByDescending(x => x)
        .FirstOrDefault() // I want DateTime.MinValue (or SqlDateTime.MinValue)
  )
); 

So I want the last timestamp, or some MinValue timestamp if there are no results.

Enumerating the above query gives the error

The null value cannot be assigned to a member with type System.DateTime

UPDATE

Ok I’m not sure that my above example was sufficient to illustrate the problem. I believe the error may be something to do with how I’m trying to do a subquery on a third linked table.

The following example recreates the exact error:

enter image description here

So I have a car, which I can take to the mechanic, which sometimes (but not always) is serviced by the mechanic.

The requirement is to find via a query to the car table how many mechanic visits each car has had since it was last serviced. The issue is when the car has never been serviced, so the data looks like:

Car
------------- 
Id: 1         


MechanicVisit          
------------- 
Id: 1 
CarId: 1 
ServiceRecordId: NULL
VisitDate: 1 Jan 2011    


ServiceRecord
------------- 
<empty>

So a simple example that shows the error is a query to get the list of last service times:

 var test = _dataContext.GetTable<Car>
                 .Select(c => 
                     c.MechanicVisits
                      .Select(m => m.ServiceRecord)
                      .Select(s => s.ServiceDate)
                      .OrderByDescending(d => d)
                      .FirstOrDefault()
                  ).ToList();

This gives the previously described error of trying to assign null to a non-nullable type, where what I need to do is return DateTime.MinValue or SqlDateTime.MinValue when the date is null (so I can do the actual query which is number of mechanic visits since the last service)


SOLUTION

I used a variation of what Jon Skeet suggested, using a cast to DateTime? and null coalescing operator:

 var test = _dataContext.GetTable<Car>
                     .Select(c => 
                         c.MechanicVisits
                          .Select(m => m.ServiceRecord)
                          .Select(s => (DateTime?)s.ServiceDate)
                          .OrderByDescending(d => d)
                          .FirstOrDefault() ?? new DateTime(1900, 1, 1)
                      ).ToList();

Note the use of the paramatered constructor for the “default” date – DateTime.MinValue can’t be used here as it throws an out of range exception when converted to SQL, and SqlDateTime.MinValue can’t be used as it is non-nullable (so the coalesce operator becomes invalid).

I still don’t really understand why the original error was occuring and this solution does feel a bit hacky, but I’ve been unable to find any neater way of fixing it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T09:43:22+00:00Added an answer on May 23, 2026 at 9:43 am

    I’d be very tempted to actually use a nullable DateTime for this. For example, from your “Car” sample:

    var test = _dataContext.GetTable<Car>
                           .Select(c => 
                               c.MechanicVisits
                                .Select(m => m.ServiceRecord)
                                .Select(s => (DateTime?) s.ServiceDate)
                                .OrderByDescending(d => d)
                                .FirstOrDefault()
                           ).ToList();
    

    That way I suspect you’ll end up with it working and giving you null DateTime? values. You could always transform that later if you wanted:

    var test = _dataContext.GetTable<Car>
                           .Select(c => 
                               c.MechanicVisits
                                .Select(m => m.ServiceRecord)
                                .Select(s => (DateTime?) s.ServiceDate)
                                .OrderByDescending(d => d)
                                .FirstOrDefault()
                           ).AsEnumerable()
                            .Select(dt => dt ?? DateTime.MinValue)
                            .ToList();
    

    Original answer (doesn’t work)

    Hmm. I won’t claim to fully understand the reasons for this, but here’s a potential workaround:

    users.Select(u =>
      new MyDomainObject(
         u.Id,
         u.Transactions
            .Where(t => false)
            .Select(t => t.TransactionTime)
            .OrderByDescending(x => x)
            .DefaultIfEmpty(DateTime.MinValue)
            .First()
      )
    ); 
    

    In other words, if the result set is empty, use the specified default – and then take the first result of the now-definitely-not-empty sequence.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am having a problem converting a value to int. I ran this query
I'm having a problem with Math.atan returning the same value as the input. public
I am having a problem returning an ArrayList from my web service (Java). I
I'm having problem in the following line: rd.PrintOptions.PaperSize = PaperSize.PaperFanfoldStdGerman; it throws an exception
We were having a problem with our build server not checking out modifications from
I'm having a problem with an application hanging and giving me the default Please
Im having a problem returning a structure. It says Run-Time Check Failure #2 -
I am having a problem selecting the unique text from database. This is for
We're having problem with a huge number of legacy stored procedures at work. Do
Having a problem getting a TreeView control to display node images. The code below

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.