Cómo obtener las 6 p.m. del día anterior usando Entity Framework

I am running into an issue where I have to perform some action on my database records where current time is greater than record's time (previous day 6pm)

Example: database record time is Mar-02-2012 03:00 pm La hora actual es Mar-01-2012 6:01 pm

Now current time is greater than 6pm of prior's day time. I create the linq query for that which is like this

var a = (from trip in trips                        
         where EntityFunctions.DiffMinutes(DateTime.UtcNow,
                    EntityFunctions.AddDays(new DateTime(Convert.ToDateTime(EntityFunctions.AddDays(trip.bookTime, -1)).Year,
                        Convert.ToDateTime(EntityFunctions.AddDays(trip.bookTime, -1)).Month,
                        Convert.ToDateTime(EntityFunctions.AddDays(trip.bookTime, -1)).Day,
                        18,0,0),-1)) > 0
         select trip).ToList();

Here what I was trying to do is get difference in minutes using EntityFunctions.DiffMinutes between current time and create a new date from the current database date minus 1 day and time of newly created date is 6pm. But I got this exception from Entity Framework.

Only parameterless constructors and initializers are supported in LINQ to Entities.

The way I am doing is very complex and even not working, so kindly help me and suggest some simple way to do so.

preguntado el 09 de marzo de 12 a las 14:03

1 Respuestas

If I understand your question correctly this is what you require:

void Main()
    var today = DateTime.Now;  // or UtcNow if you need to
    var todayMidnight = today.Date; 
    var yesterdayMidnight = todayMidnight.AddDays(-1);
    var yesterday6pm = yesterdayMidnight.AddHours(18);

    var trips = new List<Trip>
        new Trip{ bookTime = todayMidnight },
        new Trip{ bookTime = yesterdayMidnight }

    var a = trips.Where(t=>t.bookTime > yesterday6pm).ToList();

// Define other methods and classes here
class Trip{
    public DateTime bookTime{get;set;}

You can simplify the date code to:

var yesterday6pm = DateTime.Now.Date.AddDays(-1).AddHours(18);


var yesterday6pm = DateTime.Now.Date.AddHours(-6);

You certainly don't need to be using EntityFunctions for simple date comparisons.

respondido 09 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.