IQueryable for Anonymous Types

那年仲夏 提交于 2019-12-30 08:15:33

问题


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});
}

回答1:


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)); 
} 


来源:https://stackoverflow.com/questions/11982714/iqueryable-for-anonymous-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!