IQueryable for Anonymous Types

后端 未结 1 1049
情深已故
情深已故 2021-01-11 19:14

I use EntityFramework, I\'m querying and returning partial data using Anonymous Types. Currently I\'m using IQueryable, it works, but I would lik

相关标签:
1条回答
  • 2021-01-11 19:51

    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)); 
    } 
    
    0 讨论(0)
提交回复
热议问题