结合表达式而不是在实体框架中使用多个查询 [英] Combine expressions instead of using multiple queries in entity framework

查看:65
本文介绍了结合表达式而不是在实体框架中使用多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i have following generic queryable (which may already have selections applied):





我尝试过:



IQueryable< tentity> queryable = DBSet< tentity> .AsQueryable();



然后有一个Provider类看起来像这样:



公共类提供商< tentity>

{

public Expression< func>< tentity,>>条件{得到;组; }



[...]

}



条件可以按以下方式定义每个实例:



条件=实体=> entity.Id == 3;



现在我想选择所有具有至少由DBSet的一个实体满足的条件的Provider实例:



List< provider> providers = [...];

var matchingProviders = providers.Where(provider => queryable.Any(provider.Condition))



这个问题:我开始查询列表中的每个Provider实例。我宁愿使用单个查询来获得相同的结果。

由于性能有问题,这个主题特别重要。如何使用单个

查询获得相同的结果并使用Linq语句或表达式树提高性能?



What I have tried:

IQueryable<tentity> queryable = DBSet<tentity>.AsQueryable();

Then there is the Provider class that looks like this:

public class Provider<tentity>
{
public Expression<func><tentity,>> Condition { get; set; }

[...]
}

The Condition could be defined per instance in the following fashion:

Condition = entity => entity.Id == 3;

Now I want to select all Provider instances which have a Condition that is met at least by one entity of the DBSet:

List<provider> providers = [...];
var matchingProviders = providers.Where(provider => queryable.Any(provider.Condition))

The problem with this: I'm starting a query for each Provider instance in the list. I'd rather use a single query to achieve the same result.
This topic is especially important because of questionable performance. How can I achieve the same results with a single
query and improve performance using Linq statements or Expression Trees?

推荐答案

好吧,如果你想要使用动态查询,请阅读:

如何:使用表达式用于构建动态查询的树(C#和Visual Basic) [ ^ ]

带有表达式树的动态LINQ查询 - 简单对话 [ ^ ]

ScottGu&#博客 - 动态LINQ(第1部分:使用L INQ动态查询库) [ ^ ]
Well, if you would like to use dynamic queries, please read this:
How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic)[^]
Dynamic LINQ Queries with Expression Trees - Simple Talk[^]
ScottGu&#39;s Blog - Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)[^]


这篇关于结合表达式而不是在实体框架中使用多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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