如何在实体框架中使用DateTime.AddDays(x) [英] How to use DateTime.AddDays(x) in Entity Framework

查看:108
本文介绍了如何在实体框架中使用DateTime.AddDays(x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

  from e.ProgramSetup.Include(Program)。 .Client)
其中pr.DateBegin< DateTime.Now
&& pr.DateEnd> DateTime.Now.AddDays(pr.DateEndOffset)
select pr).ToList();

它不起作用,因为AddDays()不可用于生成sql。 >

还有另一种方法吗?现在我选择了所有的东西,并通过foreach过滤掉它,但这不是我的意见。



问题是,pr.DateEndOffset也只是在db,它是不是常数...

解决方案

您需要使用映射到规范函数的EntityFunctions之一。以下是AddDays的示例:

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

public class MyContext:DbContext
{
public DbSet< MyEntity>实体{get;组;


$ 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 ct in ctx.Entities
其中e.Date> EntityFunctions.AddDays(new DateTime(2012,10,1),10)
select e;

foreach(q中的var entity)
{
Console.WriteLine({0} {1},entity.Id,entity.Date);
}
}
}
}


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();

It does not work, because AddDays() is not possible to use for generating sql.

So is there some another way? Now i select everything and filter it finaly by foreach, but it is not good way in my opinion.

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

解决方案

You need to use one of the EntityFunctions mapped to the 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);
            }
        }
    }
}

这篇关于如何在实体框架中使用DateTime.AddDays(x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆