2012-08-16 17 views
6

Uso EntityFramework, estoy consultando y devolviendo datos parciales usando tipos anónimos. Actualmente estoy usando IQueryable<dynamic>, funciona, pero me gustaría saber si esta es la forma correcta de hacerlo o si hay algún otro tipo de datos de retorno que no conozco.IQueryable para tipos anónimos

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

¿Cuál es el problema de la 'IQueryable' o la parte' dynamic' del tipo de cambio? – nemesv

+0

hola nemesv, no hay problema, me gustaría saber más sobre C# y el tipo anónimo por este motivo lo estoy preguntando. Gracias por su comentario – GibboK

Respuesta

9

Normalmente, utiliza tipos anónimos solo dentro del alcance de un método. No devuelve tipos anónimos a la persona que llama. Si eso es lo que quiere hacer, debe crear una clase y volver que:

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

Estaba pensando en devolver el tipo anónimo ya que el resultado de la acción es JSON – GibboK

+0

@GibboK: No estoy seguro de seguir. No veo una "acción" o JSON aquí –

+0

sí No subí el código completo, gracias por su respuesta – GibboK

Cuestiones relacionadas