Build Expression tree for LINQ to Entities Where clause

心已入冬 提交于 2021-01-28 14:13:55

问题


I want to be able to write the following code for a LINQ to Entities query (EF6)

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

Without the WhereActive() method, I would have to repeat the following expression in numerous places:

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

I tried to write a simple extension method, but it gave an error "LINQ to Entities does not recognize the method 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);
    }

After some reading on LINQ to Entities vs LINQ to Object, and Expression trees vs Func<>, I realized I would need to build a full Expression tree to express my intention.

I'm not sure how to do it, may I get some help please?


回答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. That SHOULD have worked...however if it didn't you have two choices...

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
            })


来源:https://stackoverflow.com/questions/24300251/build-expression-tree-for-linq-to-entities-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!