简体   繁体   English

扩展表达式 <func<t, bool> &gt;

[英]Extending an expression<func<t, bool>>

It has been a long while since I have delved into expression trees and I am struggling with the following problem. 自从我深入研究表达式树以来已经有很长时间了,我一直在努力解决以下问题。

Basically I want to take the following Expression<Func<T, TIdType>> : 基本上,我想采用以下Expression<Func<T, TIdType>>

(a) => EF.Property<TIdType>(a, "TenantId")

and extend it to become this Expression<Func<T, bool> : 并将其扩展为这个Expression<Func<T, bool>

(a) => EF.Property<TIdType>(a, "TenantId").Equals(TenantId)

So basically I want to take the original expression and add on .Equals(TenantId) 所以基本上我想采用原始表达式并添加.Equals(TenantId)

For the background to this issue, its all due to me attempting to workaround an issue in EF Core 2.0 as raised here: 对于此问题的背景,全部归因于我试图解决此处提出的EF Core 2.0中的问题:

https://github.com/aspnet/EntityFrameworkCore/issues/11456 https://github.com/aspnet/EntityFrameworkCore/issues/11456

The following hopefully shows what I am attempting in more detail: 希望以下内容能更详细地说明我的尝试:

public class FooEntity
{
    public Guid TenantId { get; set; }
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {

        var adaptor = new TenantFilterExpressionAdaptor<FooEntity, Guid>();
        var tenantIdFilter = adaptor.Adapt((a) => EF.Property<Guid>(a, "TenantId"));

    }
}

public class TenantFilterExpressionAdaptor<T, TIdType>
{

    public TIdType TenantId { get; set; }

    public Expression<Func<T, bool>> Adapt(Expression<Func<T, TIdType>> idExpression)
    {

        // Tack on .Equals(TenantId) to the expression!?

        // assume I have to add nodes to the body?
        // idExpression.Body?

    }

}

You have to build new expression, because expressions are immutable. 您必须构建新的表达式,因为表达式是不可变的。 In this case you can reuse body and parameters of existing expression for the new one: 在这种情况下,您可以为新表达式重用现有表达式的主体和参数:

public class TenantFilterExpressionAdaptor<T, TIdType> {

    public TIdType TenantId { get; set; }

    public Expression<Func<T, bool>> Adapt(Expression<Func<T, TIdType>> idExpression) {
        return Expression.Lambda<Func<T, bool>>(
            Expression.Equal(idExpression.Body, Expression.Constant(TenantId)),
            idExpression.Parameters);
    }
}

You mentioned in comments that constant is problematic for you. 您在评论中提到常数对您有问题。 In this case you can reference property itself and not its value: 在这种情况下,您可以引用属性本身而不是其值:

return Expression.Lambda<Func<T, bool>>(
    Expression.Equal(idExpression.Body, Expression.Property(Expression.Constant(this), nameof(TenantId))),
    idExpression.Parameters);

This will be expression like: 这将是这样的表达式:

x => x.TenantId == this.TenantId

where this is instance of your adapter. this是您的适配器的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM