包括衍生财产成的LINQ to实体查询 [英] Include derived property into a linq to entity query
问题描述
下面是一个基于名为任务
A波科类的简单项目:
Here is a simple project based on a Poco class named Task
:
class Program
{
static void Main(string[] args)
{
using (MyDbContext ctx = new MyDbContext())
{
// first query
DateTime compareDate = DateTime.Now + TimeSpan.FromDays(3);
var res = ctx.Tasks.Where(t => t.LastUpdate < compareDate).ToList();
// second query
res = ctx.Tasks.Where(t => t.ShouldUpdate).ToList();
}
}
}
public class MyDbContext : DbContext
{
public DbSet<Task> Tasks { get; set; }
}
public class Task
{
public int ID { get; set; }
public DateTime LastUpdate { get; set; }
public bool ShouldUpdate
{
get
{
return LastUpdate < DateTime.Now + TimeSpan.FromDays(3);
}
}
}
我想要做的就是查询上下文 dbset
包括在where子句中的 ShouldUpdate
衍生属性。
What I want to do is to query the context dbset
including in the where clause the ShouldUpdate
derived property.
第一查询工作正常(我不能写在一行,但它并不重要)。
The "first query works fine" (I can't write it in a single line but it doesn't matter).
正如你所知道,我们得到了一个引发NotSupportedException
关于十二查询,以下消息:在LINQ是不支持的实体
指定的类型成员ShouldUpdate。只有初始化,实体成员和实体导航属性都支持。
As you know, we get a NotSupportedException
on the "second query", with the following message:
The specified type member 'ShouldUpdate' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
这是正确的,我可以理解为什么它会发生,但我需要封装在<$派生信息C $ C>工作对象,这样我就可以在网格中显示的属性或使用它在所有其他地方,而不用复制它背后的逻辑。
That's right and I can understand why it happen, but I need to encapsulate the derived information inside the Task
object so I can display the property in a grid or use it in every other place, without duplicating the logic behind it.
有一个聪明的方法来做到这一点?
Is there a smart technique to do this?
注:什么是 ShouldUplate
属性的技术名称?衍生?如何计算?计算的?
NB: What is the technical name of the ShouldUplate
property? derived? calculated? computed?
推荐答案
最后我找到了解决办法..
你可以存储静态个行业部分查询(表达式)并利用它们是这样的:
Finally i found THE solution.. You can store the partial queries (Expressions) in static fileds and use them like this:
class Program
{
static void Main(string[] args)
{
using (MyDbContext ctx = new MyDbContext())
{
res = ctx.Tasks.Where(Task.ShouldUpdateExpression).ToList();
}
}
}
public class MyDbContext : DbContext
{
public DbSet<Task> Tasks { get; set; }
}
public class Task
{
public int ID { get; set; }
public DateTime LastUpdate { get; set; }
public bool ShouldUpdate
{
get
{
return ShouldUpdateExpression.Compile()(this);
}
}
public static Expression<Func<Task, bool>> ShouldUpdateExpression
{
get
{
return t => t.LastUpdate < EntityFunctions.AddDays(DateTime.Now, 3);
}
}
}
这篇关于包括衍生财产成的LINQ to实体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!