GANI
GANI

Reputation: 2049

How to return DateTimeOffset type with Linq

how to return DateTimeOffset with a Linq query. I need to get a due date from a table of type DateTimeOffset

public DateTimeOffset GetLastDate(Guid Id, Guid AppId)                     
{
   var q = from k in context.Inspections
           where k.Id == Id || k.AppId == AppId
           select k.Duedate;
   return q;
}

cannot implicitly convert system.Linq.IQueryable to System.DateTimeOffset

Upvotes: 1

Views: 1265

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564413

The problem is that your query will return an IQueryable<T>, with the type being the type of Duedate.

If Duedate is a DateTimeOffset, you could return the first result (Where can return multiple matches) via:

    var q = from k in context.Inspections
            where k.Id== Id||k.AppId== AppId
            select k.Duedate;
    DateTimeOffset? value = q.First();

    if (value.HasValue)
        return value.Value;
    else // found NULL in DB! Do something in this case...
        throw new ApplicationException("Null offset found");

    // Alternatively, you could use some default value (this uses "Now"):
    // return value ?? DateTimeOffset.Now;

Upvotes: 2

Related Questions