简体   繁体   中英

Value for Non-Nullable System.DateTime

The following code works fine for a nullable DateTime :

lastSync = syncHistsQuery.Max(m => m.Value);

Why does the same code not work for a non-nullable DateTime ? Here is the error :

'System.DateTime' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference ?)

Do I have to change DateTime to a Nullable DateTime in the database ? Is there a different way to write the code for non-nullable DateTimes ?

Here is the entire function in case it helps :

public static DateTime GetMaxSyncDateTime()
{
    DateTime lastSync = DateTime.MinValue;
    using (var db = new CarbonContext())
    {
        var syncHistsQuery = from s in db.SyncHistories
                                 select s.SyncHistDateTime;

        lastSync = syncHistsQuery.Max(m => m.Value);
    }
    return lastSync;
}

"Nullable" DateTime? is in fact a syntax sugar for

  Nullable<DateTime>

which has two properies

  public Boolean HasValue
  public DateTime Value

http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.110).aspx

DateTime itself has a lot of properies but no Value property

http://msdn.microsoft.com/en-us/library/vstudio/system.datetime(v=vs.100).aspx

Since DateTime implements IComparable<DateTime> just use Max() :

lastSync = syncHistsQuery.Max();

Because non nullable DateTime doesn't have a Value property.You use

lastSync = syncHistsQuery.Max();

If you are working with DateTimes .

A DateTime doesn't have a .Value property, that is something from Nullable<T> .

You can just do:

lastSync = syncHistsQuery.Max(m => m);

Or, as pointed out, you can shorten it to:

lastSync = syncHistsQuery.Max();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM