Search code examples
c#entity-frameworklinqlinq-to-entities

Getting maximum date and return default date when table is empty


How to return date "1900/12/12 00:00:00" if table has no rows? I am trying to get max transaction date and it works well if there are rows in the table otherwise I get an error message because of date format in ToString().

string d = context.AllTransactions.Where(t => t.ID == OID)
                  .Max(t => t.TransactionDate).ToString("dd/MM/yyyy HH:mm:ss");

TransactionDate is NOT NULL datetime field.


Solution

  • Use the DefaultIfEmpty method before the .Max (and as it is linq to entities and you will not be able to create a new transaction object then first project only the dates):

    var result = context.AllTransactions.Where(t => t.ID == OID)
                        .Select(t => t.TransactionDate)
                        .DefaultIfEmpty(new DateTime(1900,12,12)).Max();