關於Expression >表達式目錄樹的形式的強類型 lambda 表達式的拼接


當前在封裝類EF的Where條件的表達式的解析邏輯,遇到的問題是:運用過程中可能需要將復雜的條件在不同的處理邏輯中Expression表達式進行拼接。

針對於遇到的問題寫了示例進行記錄,主要為了能夠將Lambda表達式轉為可執行的SQL語句,例子如下:

(相關的Lambda表達式轉為SQL語句的整理待有空的時候再整理,這邊先記錄一下表達式的拼接)

            // f or f2 or f3
            Expression<Func<SimplifyClass, bool>> f = SC => SC.id > 0 && string.IsNullOrEmpty(SC.name);
            Expression<Func<SimplifyClass, bool>> f2 = SC => SC.sourcename != "AA" && SC.text == "CC";
            Expression<Func<SimplifyClass, bool>> f3 = SC => SC.sourcename.Contains("D");

            ParameterExpression pp = Expression.Parameter(typeof(SimplifyClass), "SC");
            MemberExpression fleftL = Expression.Property(pp, typeof(SimplifyClass).GetProperty("id"));
            ConstantExpression fleftR = Expression.Constant(0);
            BinaryExpression where1 = Expression.LessThan(fleftR, fleftL);

            MemberExpression frightR = Expression.Property(pp, typeof(SimplifyClass).GetProperty("name"));
            MethodCallExpression where2 = Expression.Call(typeof(string).GetMethod("IsNullOrEmpty"), frightR);
            where1 = Expression.And(where1, where2);

            MemberExpression f2leftL = Expression.Property(pp, typeof(SimplifyClass).GetProperty("sourcename"));
            ConstantExpression f2leftR = Expression.Constant("AA");
            BinaryExpression where3 = Expression.NotEqual(f2leftL, f2leftR);

            MemberExpression f2rightL = Expression.Property(pp, typeof(SimplifyClass).GetProperty("text"));
            ConstantExpression f2rightR = Expression.Constant("CC");
            BinaryExpression where4 = Expression.Equal(f2leftL, f2rightR);
            where3 = Expression.And(where3, where4);
            where1 = Expression.Or(where1, where3);

            MemberExpression f3leftR = Expression.Property(pp, typeof(SimplifyClass).GetProperty("sourcename"));
            ConstantExpression f3rightR = Expression.Constant("D");
            MethodCallExpression where5 = Expression.Call(f3leftR, typeof(string).GetMethod("Contains"), f3rightR);
            where1 = Expression.Or(where1, where5);

            Expression<Func<SimplifyClass, bool>> lambda = Expression.Lambda<Func<SimplifyClass, bool>>(where1, pp);
            //lambda轉為SQL語句為:((@P0 < [id]) AND (ISNULL([name],'')<>'')) OR (([sourcename] <> @P1) AND ([text] = @P2)) OR ([sourcename] LIKE '%D%')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM