本文介绍了我可以使用Entity Framework的子查询的扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图巩固逻辑访问使用Entity Framework的不同的表。我创建了一个扩展方法从该人是参加我的注册实体拉着所有注册:

I'm trying to consolidate logic for accessing different tables using Entity Framework. I created an extension method for pulling all registrations from my registration entity where the person is attending:

public static IEnumerable<Registration> Attending(this IEnumerable<Registration> registrations)
{
    return registrations.Where(r => r.Status == RegistrationStatus.Paid || r.Status == RegistrationStatus.Assigned || r.Status == RegistrationStatus.Completed);
}

这对于像这样的查询的伟大工程:

This works great for queries like this:

var attendees = db.Registrations.Attending().ToList();

但它不工作的子查询中使用时:

But it doesn't work when used in a subquery:

ProductTotals = db.Products.Where(p => p.EventID == ev.Id).Select(p => new ProductSummaryViewModel
{
    ProductID = p.ProductID,
    ProductName = p.Name,
    Registrations = p.Registrations.Attending().Count(),
}).ToList();

我收到以下错误:

I get the following error:

LINQ实体无法识别方法
  System.Collections.Generic.IEnumerable 1 [注册]
  参加(System.Collections.Generic.IEnumerable
1 [注册])'
  法,这种方法不能被翻译成店前pression。

有没有办法再使用了code子查询?

Is there any way re-use that code in a subquery?

推荐答案

你想实现的是重用predicate定义的含义出席最主要的。您可以通过存储在只读变量是提供给谁需要它在你的应用程序,例如在一个静态类除权pression做防爆pressionConstants

The main thing you're trying to achieve is reusing the predicate that defines the meaning of Attending. You can do that by storing the expression in a readonly variable that is available to whoever needs it in your application, for example in a static class ExpressionConstants.

public static readonly Expression<Func<Registration, bool>> IsAttending =
    r => r.Status == RegistrationStatus.Paid
      || r.Status == RegistrationStatus.Assigned
      || r.Status == RegistrationStatus.Completed;

然后,你可以做

var attendees = db.Registrations.Where(ExpressionConstants.IsAttending).ToList();

和子查询中使用:

ProductTotals = db.Products.Where(p => p.EventID == ev.Id).Select(p => new ProductSummaryViewModel
{
    ProductID = p.ProductID,
    ProductName = p.Name,
    Registrations = p.Registrations.AsQueryable() // AsQueryable()
                     .Where(ExpressionConstants.IsAttending).Count(),
})

AsQueryable已()是必要的,因为 p.Registrations 可能是一个 ICollection的

The AsQueryable() is necessary because p.Registrations probably is an ICollection.

这篇关于我可以使用Entity Framework的子查询的扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:29