10

我使用 EntityFramework,我正在使用匿名类型查询和返回部分数据。目前我正在使用IQueryable<dynamic>,它可以工作,但我想知道这是否是正确的方法,或者是否有其他一些我不知道的返回数据类型。

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

1 回答 1

13

通常,您只在一种方法的范围内使用匿名类型。您不会将匿名类型返回给调用者。如果这就是你想要做的,你应该创建一个类并返回它:

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)); 
} 
于 2012-08-16T08:02:16.543 回答