为LINQ to Entities Where子句构建表达式树 [英] Build Expression tree for LINQ to Entities Where clause

查看:44
本文介绍了为LINQ to Entities Where子句构建表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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)

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

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

在对LINQ to Ents vs LINQ to Object,Expression tree vs Func<>进行了一些阅读之后,我意识到我需要构建一个完整的Expression Tree来表达自己的意图.

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?

推荐答案

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

这篇关于为LINQ to Entities Where子句构建表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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