How to use DateTime.AddDays (x) in Entity Framework

I have this code:

from pr in e.ProgramSetup.Include("Program").Include("Program.Client")
        where pr.DateBegin < DateTime.Now
        && pr.DateEnd > DateTime.Now.AddDays(pr.DateEndOffset) 
select pr).ToList();

This does not work because AddDays () cannot be used to generate sql.

So is there another way? Now I select everything and filter it out completely on foreach, but in my opinion this is not good.

The problem is that pr.DateEndOffset is also only in db, it is not constant ...

+5
source share
2 answers

You need to use one of the EntityFunctions mapped to canonical functions. Here is an example for AddDays:

public class MyEntity
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<MyEntity> Entities { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new MyContext())
        {
            if (!ctx.Entities.Any())
            {
                ctx.Entities.Add(new MyEntity() { Date = new DateTime(2000, 1, 1) });
                ctx.Entities.Add(new MyEntity() { Date = new DateTime(2012, 10, 1) });
                ctx.Entities.Add(new MyEntity() { Date = new DateTime(2012, 12, 12) });
                ctx.SaveChanges();
            }

            var q = from e in ctx.Entities
                    where e.Date > EntityFunctions.AddDays(new DateTime(2012, 10, 1), 10)
                    select e;

            foreach (var entity in q)
            {
                Console.WriteLine("{0} {1}", entity.Id, entity.Date);
            }
        }
    }
}
+8
source
using System.Data.Entity;
...
DbFunctions.AddDays(dateFromDataStore, numDaysToAdd);
+1
source

All Articles