我有以下数据库图表:
每个Product
都使用LanguageKey
来确定其名称,并且每个LanguageKey
都有多个包含值的LanguageValue
记录对于每种语言。
现在在我的 Controller
中,我想将我的 Product
实体选择到 ViewModel
对象中,因此我的语句如下所示:
var model = new ProductListViewModel()
{
Products = products
.Select(q => new ProductViewModel()
{
ID = q.ID,
Name = q.LanguageKey.LanguageValues.FirstOrDefault(p => p.LanguageID == this.CurrentLanguage.ID && p.Active).Value,
Code = q.Code,
// Other code
简而言之,我已经有了所需的语言 ID,并且我需要获取准确的值。然而,当查看 VS 的诊断工具时,当执行查询树时(当我在 View 中调用 foreach
语句时),我的应用程序执行了多个 SELECT 语句,每个语句对应一个 LanguageValue
,如下所示:
"SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Active] AS [Active]
FROM [dbo].[LanguageKey] AS [Extent1]
WHERE [Extent1].[ID] = @EntityKeyValue1"
"SELECT
[Extent1].[ID] AS [ID],
[Extent1].[LanguageKeyID] AS [LanguageKeyID],
[Extent1].[LanguageID] AS [LanguageID],
[Extent1].[Value] AS [Value],
[Extent1].[Active] AS [Active]
FROM [dbo].[LanguageValue] AS [Extent1]
WHERE [Extent1].[LanguageKeyID] = @EntityKeyValue1"
是因为我使用的是FirstOrDefault()
吗?有没有更好的方法来处理这个问题,因为我的应用程序在过滤后经常会处理大约 1k 条记录。
P.s:我还想知道为什么编译的查询中没有 Active
谓词。
编辑:这就是我获取products
的方式(Context是我的DbContext,该函数位于ProductService
类内部,productService
是它的实例):
public IEnumerable<Product> GetAllActiveProducts()
{
return this.Context.Products
.Where(q => q.Active);
}
var products = productService.GetAllActiveProducts();
最佳答案
您的GetAllActiveProducts()
应该返回IQueryable<Product>
,不是IEnumerable<Product>
。通过返回IEnumerable<Product>
,您实际上是强制在客户端执行该可枚举的任何进一步操作。这正是您所看到的行为的原因。
关于c# - 优化具有外键访问的 LINQ to SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33375998/