IQueryable for Anonymous Types
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));
}
GibboK
A professional and enthusiastic Senior Front End Developer. Listed as top 2 users by reputation in Czech Republic on Stack Overflow. Latest open source projects Animatelo - Porting to JavaScript Web Animations API of Animate.css (430+ stars on GitHub) Industrial UI - Simple, modular UI Components for Shop Floor Applications Frontend Boilerplate - An opinionated boilerplate which helps you build fast, robust, and adaptable single-page application in React Keyframes Tool - Command line tool which convert CSS Animations to JavaScript objects gibbok.coding📧gmail.com
Updated on June 04, 2022Comments
-
GibboK almost 2 years
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}); }
-
GibboK over 11 yearsI was thinking to returning anonymous type as the result of the action is JSON
-
Daniel Hilgarth over 11 years@GibboK: I am not sure I follow. I don't see an "action" or JSON here
-
GibboK over 11 yearsyes I have not uploaded the full code, thanks for your answer