Adding Inner Join to DbScanExpression in Entity Framework Interceptor

前端 未结 1 1032
感动是毒
感动是毒 2021-02-07 12:45

I\'m trying to use an Entity Framework CommandTree interceptor to add a filter to every query via a DbContext.

For the sake of simplicity, I have two tables, one called

相关标签:
1条回答
  • 2021-02-07 13:32

    The reason you obtained that exception is because InnerJoin produces a result combined of columns from both tables and on the other hand the query is supposed to return those matching properties of class User, so you additionally need to use projection at the end of query. Here is the code which worked for me:

    public override DbExpression Visit(DbScanExpression expression)
    {
        var table = expression.Target.ElementType as EntityType;
        if (table != null && table.Name == "User")
        {
            return expression.InnerJoin(
                DbExpressionBuilder.Scan(expression.Target.EntityContainer.BaseEntitySets.Single(s => s.Name == "TennantUser")),
                (l, r) =>
                    DbExpressionBuilder.Equal(
                        DbExpressionBuilder.Property(l, "UserId"),
                        DbExpressionBuilder.Property(r, "UserId")
                    )
            )
            .Select(exp => 
                new { 
                    UserId = exp.Property("l").Property("UserId"), 
                    Email = exp.Property("l").Property("Email") 
                });
        }
    
        return base.Visit(expression);
    }
    

    As you see after join operation you refer to specific joined table by using its lambda expression alias from expression specifying join condition. So in my case you refer to User table as l and to TennantUser as r. Letters l and r will be used as well as aliases in resulting SQL query sent to database. In between InnerJoin and Select operations you may place additional logic you need like Filter etc.

    0 讨论(0)
提交回复
热议问题