IQueryable for Anonymous Types

GibboK picture GibboK · Aug 16, 2012 · Viewed 9.3k times · Source

I use EntityFramework, I'm querying and returning partial data using Anonymous Types. Currently I'm using IQueryable<dynamic>, it works, but I would like to know if this is the proper way to do it or if there is some other returning datatype that I'm not aware of.

public IQueryable<dynamic> FindUpcomingEventsCustom(int daysFuture)
{
    DateTime dateTimeNow = DateTime.UtcNow;
    DateTime dateTimeFuture = dateTimeNow.AddDays(daysFuture);
    return db.EventCustoms.Where(x => x.DataTimeStart > dateTimeNow & x.DataTimeStart <= dateTimeFuture)
        .Select(y => new { y.EventId, y.EventTitle, y.DataTimeStart});
}

Answer

Daniel Hilgarth picture Daniel Hilgarth · Aug 16, 2012

Normally, you use anonymous types only inside the scope of one method. You don't return anonymous types to the caller. If that's what you want to do, you should create a class and return that:

public class Event
{
    private readonly int _eventId;
    private readonly string _eventTitle;
    private readonly DateTime _dateTimeStart;

    public Event(int eventId, string eventTitle, DateTime dateTimeStart)
    {
        _eventId = eventId;
        _eventTitle = eventTitle;
        _dateTimeStart = dateTimeStart;
    }

    public int EventId { get { return _eventId; } }
    public string EventTitle { get { return _eventTitle; } }
    public DateTime DateTimeStart{ get { return _dateTimeStart; } }
}



public IQueryable<Event> FindUpcomingEventsCustom(int daysFuture) 
{ 
    DateTime dateTimeNow = DateTime.UtcNow; 
    DateTime dateTimeFuture = dateTimeNow.AddDays(daysFuture); 
    return db.EventCustoms
             .Where(x => x.DataTimeStart > dateTimeNow
                         && x.DataTimeStart <= dateTimeFuture) 
             .Select(y => new Event(y.EventId, y.EventTitle, y.DataTimeStart)); 
}