为LINQ to Entities Where子句构建表达式树

时间:2014-06-19 06:39:50

标签: entity-framework linq-to-entities expression-trees

我希望能够为LINQ to Entities查询(EF6)编写以下代码

Repo.ContactRelations.WhereActive()
                .Select(r => new ContactModel
                {
                    Id = r.Contact.Id,
                    FirstName = r.Contact.FirstName,
                    LastName = r.Contact.Surname,
                    WorkEmail = r.Contact.WorkEmail
                })

如果没有WhereActive()方法,我将不得不在许多地方重复以下表达式:

Repo.ContactRelations.Where(c => c.EndDate == null || c.EndDate > DateTime.Today)

我尝试编写一个简单的扩展方法,但它给出了一个错误“LINQ to Entities无法识别WhereActive方法”

    public static IEnumerable<T> WhereActive<T>(this IEnumerable<T> source) where T : class, IMayExpire
    {
        return source.Where(c => c.EndDate == null || c.EndDate > DateTime.Today);
    }

在阅读LINQ to Entities vs LINQ to Object,以及Expression tree vs Func&lt;&gt;之后,我意识到我需要构建一个完整的Expression树来表达我的意图。

我不知道该怎么做,请问我可以得到一些帮助吗?

1 个答案:

答案 0 :(得分:1)

public static IQueryable<T> WhereActive<T>(this IQueryable<T> source) where T : class, IMayExpire
{
    return source.Where(c => c.EndDate == null || c.EndDate > DateTime.Today);
}

EDIT。那应该有用......但如果它没有两个选择......

var activeContactRelations = Repo.ContactRelations.WhereActive();
var result = activeContactRelations
            .Select(r => new ContactModel
            {
                Id = r.Contact.Id,
                FirstName = r.Contact.FirstName,
                LastName = r.Contact.Surname,
                WorkEmail = r.Contact.WorkEmail
            })

OR

using System.Linq;

public static Expression<Func<T, bool>> IsActive<T>() where T : class, IMayExpire
{
    return c => c.EndDate == null || c.EndDate > DateTime.Today;
}

var isActive = IsActive<ContactRelation>();
var result = Repo.ContactRelations.Where(isActive)
            .Select(r => new ContactModel
            {
                Id = r.Contact.Id,
                FirstName = r.Contact.FirstName,
                LastName = r.Contact.Surname,
                WorkEmail = r.Contact.WorkEmail
            })