Zde*_*k G 11 c# datetime linq-to-entities entity-framework
我有这个代码:
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();
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为无法使用AddDays()来生成sql.
还有另一种方式吗?现在我选择所有内容并通过foreach最终过滤它,但在我看来这不是好方法.
问题是pr.DateEndOffset也只在db中,它不是常量...
Paw*_*wel 10
您需要使用映射到规范函数的EntityFunction之一.以下是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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Gra*_*ght 10
using System.Data.Entity;
...
DbFunctions.AddDays(dateFromDataStore, numDaysToAdd);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8240 次 |
| 最近记录: |