user3070072
user3070072

Reputation: 620

how to query nullable datetime in linq

I am calling the following query, to display only latest date from fieldname 'UploadDate', however I am experiencing exception error such as:

The entity or complex type 'cdwModel.database_BD' cannot be constructed in a LINQ to Entities query.","ExceptionType":"System.NotSupportedException","StackTrace":

Code:

public IEnumerable<database_BD> GetDate()
    {
        var data = (from c in db.database_BD
           select new database_BD()
           {
               UploadDate = c.UploadDate

           }).ToList().OrderByDescending(c => c.UploadDate).Take(1);

         return data;
    }

database_BD model class:

public partial class database_BD
 {
    public Nullable<System.DateTime> UploadDate { get; set; }
 }

Working solution:

public DateTime? GetDate()
    {
        return data = db.database_BD.Select(d => d.UploadDate)
                     .OrderByDescending(c => c)
                     .FirstOrDefault();
    }

Upvotes: 3

Views: 7595

Answers (2)

crthompson
crthompson

Reputation: 15875

If you just want to display the latest date from UploadDate, then you dont need to create a new database object.

In this example data will be a single date value, or null if there are no records:

var data = db.database_BD.Select(d => d.UploadDate)
                         .OrderByDescending(c => c)
                         .FirstOrDefault();

If you need to return a database_BD object, you'd remove the select which changes the output:

public database_BD GetDate()
{
    var data = db.database_BD.OrderByDescending(c => c.UploadDate)
                             .FirstOrDefault(a => a.UploadDate.HasValue);
     return data;
}

That will give you the newest database_BD object in your table.

Upvotes: 4

Erik Philips
Erik Philips

Reputation: 54638

Since your field is nullable you probablye want:

IEnumerable<database_BD> data = db.database_BD
  .Where(d => d.UpdateDate.HasValue)
  .OrderByDescending(d => d.UpdateDate.Value)
  .Take(1);

updated per your change in the question

Upvotes: 4

Related Questions