什么都2020了,LINQ查询你还在用表达式树

1、简介

今天给大家推荐个好的轮子,System.Linq.Dynamic.Core。我们都知道

数据库应用程序经常依赖于“动态SQL”,即在运行时通过程序逻辑构造的查询。拼接SQL容易造成SQL注入,普通的LINQ可以用表达式树来完成,但也比较麻烦。推荐System.Linq.Dynamic.Core用起来比较方便。

这是Microsoft程序集的.NET 4.0动态语言功能的.NET Core /标准端口。

使用此库,可以在iQueryTable上编写动态LINQ查询(基于字符串):

var query = db.Customers    .Where("City == @0 and Orders.Count >= @1", "London", 10)    .OrderBy("CompanyName")    .Select("new(CompanyName as Name, Phone)");

2、使用

2.1、nuget

Install-Package System.Linq.Dynamic.Core -Version 1.2.5

2.2、常见方式

using System.Collections;using System.Collections.Generic;using System.Linq.Dynamic.Core.Tests.Helpers;using System.Linq.Dynamic.Core.Tests.Helpers.Models;using System.Linq.Expressions;using System.Reflection;namespace System.Linq.Dynamic.Core.ConsoleTestApp{    public static class E    {        public static IQueryable GroupBy2<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keyLambda2)        {            //LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, "new (Profile.Age)", null);            LambdaExpression x = (LambdaExpression)keyLambda2;            //return source.Provider.CreateQuery<IGrouping<TKey, TSource>>(            //    Expression.Call(            //        typeof(Queryable), "GroupBy",            //        new Type[] { source.ElementType, keySelector.Body.Type },            //        new Expression[] { source.Expression, Expression.Quote(keySelector) }            //        ));            return source.Provider.CreateQuery(               Expression.Call(                   typeof(Queryable), "GroupBy",                   new Type[] { source.ElementType, x.Body.Type },                   new Expression[] { source.Expression, Expression.Quote(x) }));        }    }    public class Program{        public static void Main(string[] args)        {            Console.WriteLine("--start");            DynamicProperty[] props = { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };            Type type = DynamicClassFactory.CreateType(props);            DynamicProperty[] props2 = { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };            Type type2 = DynamicClassFactory.CreateType(props2);            DynamicProperty[] props3 = { new DynamicProperty("Name", typeof(int)), new DynamicProperty("Birthday", typeof(DateTime)) };            Type type3 = DynamicClassFactory.CreateType(props3);                        DynamicClass dynamicClass = Activator.CreateInstance(type) as DynamicClass;            dynamicClass.SetDynamicPropertyValue("Name", "Albert");            dynamicClass.SetDynamicPropertyValue("Birthday", new DateTime(1879, 3, 14));            Console.WriteLine(dynamicClass);            string n1 = dynamicClass["Name"] as string;            Console.WriteLine("dynamicClass[\"Name\"] = '" + n1 + "'");            dynamicClass["NameX"] = "x";            string n2 = dynamicClass["NameX"] as string;            Console.WriteLine("dynamicClass[\"NameX\"] = '" + n2 + "'");            //GroupByAndSelect_TestDynamicSelectMember();            //Select();            //TestDyn();            //ExpressionTests_Enum();            //Where();            //ExpressionTests_Sum();            Console.WriteLine("--end");        }        private static void GroupByAndSelect_TestDynamicSelectMember()        {            var testList = User.GenerateSampleModels(51).Where(u => u.Profile.Age < 23);            var qry = testList.AsQueryable();            var rrrr = qry.GroupBy2(x => new { x.Profile.Age });            var ll = rrrr.ToDynamicList();            var byAgeReturnAllReal = qry.GroupBy(x => new { x.Profile.Age }).ToList();            var r1 = byAgeReturnAllReal[0];            //var byAgeReturnOK = qry.GroupBy("Profile.Age").ToDynamicList();            // -    [0]  {System.Linq.Grouping<<>f__AnonymousType0<int?>, System.Linq.Dynamic.Core.Tests.Helpers.Models.User>}  object {System.Linq.Grouping<<>f__AnonymousType0<int?>, System.Linq.Dynamic.Core.Tests.Helpers.Models.User>}            var byAgeReturnAll = qry.GroupBy("new (Profile.Age)").OrderBy("Key.Age").ToDynamicList();            var q1 = byAgeReturnAll[0];            var k = q1.Key;            int? age = k.Age;            foreach (var x in byAgeReturnAllReal.OrderBy(a => a.Key.Age))            {                Console.WriteLine($"age={x.Key.Age} : users={x.ToList().Count}");            }            foreach (var x in byAgeReturnAll)            {                Console.WriteLine($"age={x.Key.Age} : users={x}");            }        }        private static void TestDyn()        {            var user = new User { UserName = "x" };            dynamic userD = user;            string username = userD.UserName;            Console.WriteLine("..." + username);        }        public static void ExpressionTests_Enum()        {            //Arrange            var lst = new List<TestEnum> { TestEnum.Var1, TestEnum.Var2, TestEnum.Var3, TestEnum.Var4, TestEnum.Var5, TestEnum.Var6 };            var qry = lst.AsQueryable();            //Act            var result1 = qry.Where("it < TestEnum.Var4");            var result2 = qry.Where("TestEnum.Var4 > it");            var result3 = qry.Where("it = Var5");            var result4 = qry.Where("it = @0", TestEnum.Var5);            var result5 = qry.Where("it = @0", 8);            //Assert            int idx = 0;            var ar1 = result1.ToArray();            foreach (var c in new[] { TestEnum.Var1, TestEnum.Var2, TestEnum.Var3 })            {                Console.Write("*");                Write((int)c, (int)ar1[idx]);                idx++;            }            idx = 0;            ar1 = result2.ToArray();            foreach (var c in new[] { TestEnum.Var1, TestEnum.Var2, TestEnum.Var3 })            {                Console.Write("*");                Write((int)c, (int)ar1[idx]);                idx++;            }            Write((int)TestEnum.Var5, (int)result3.Single());            Write((int)TestEnum.Var5, (int)result4.Single());            Write((int)TestEnum.Var5, (int)result5.Single());        }        public static void Where()        {            //Arrange            var testList = User.GenerateSampleModels(100, allowNullableProfiles: true);            var qry = testList.AsQueryable();            //Act            //var xxx = DynamicQueryable            var userById = qry.Where("Id=@0", testList[10].Id);            var userByUserName = qry.Where("UserName=\"User5\"");            var nullProfileCount = qry.Where("Profile=null");            var userByFirstName = qry.Where("Profile!=null && Profile.FirstName=@0", testList[1].Profile.FirstName);            //Assert            Write(testList[10], userById.Single());            Write(testList[5], userByUserName.Single());            Write(testList.Count(x => x.Profile == null), nullProfileCount.Count());            Write(testList[1], userByFirstName.Single());        }        public static void ExpressionTests_Sum()        {            //Arrange            int[] initValues = { 1, 2, 3, 4, 5 };            var qry = initValues.AsQueryable().Select(x => new { strValue = "str", intValue = x }).GroupBy(x => x.strValue);            //Act            var result = qry.Select("Sum(intValue)").AsEnumerable().ToArray()[0];            //Assert            Write(15, result);        }        public static void Select()        {            //Arrange            List<int> range = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };            var testList = User.GenerateSampleModels(100);            var qry = testList.AsQueryable();            //Act            IEnumerable rangeResult = range.AsQueryable().Select("it * it");            var userNames = qry.Select("UserName");            var userFirstName = qry.Select("new (UserName, Profile.FirstName as MyFirstName)");            var userRoles = qry.Select("new (UserName, Roles.Select(Id) AS RoleIds)");            //Assert            WriteArray(range.Select(x => x * x).ToArray(), rangeResult.Cast<int>().ToArray());            WriteArray(testList.Select(x => x.UserName).ToArray(), userNames.ToDynamicArray());            WriteArray(testList.Select(x => "{UserName=" + x.UserName + ", MyFirstName=" + x.Profile.FirstName + "}").ToArray(), userFirstName.AsEnumerable().Select(x => x.ToString()).ToArray());            Guid[] check = testList[0].Roles.Select(x => x.Id).ToArray();            //dynamic f = userRoles.First();            //Guid[] ids = f.RoleIds.ToArray();            var userRole = userRoles.First();            Console.WriteLine(">>>>>>>>>>>>>>>>>>" + userRole.ToString());            PropertyInfo[] props = userRole.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);            Console.WriteLine(">>>>>>>>>>>>>>>>>> GetProperties = {0}", string.Join(", ", props.Select(p => p.Name)));            Console.WriteLine(">>>>>>>>>>>>>>>>>> GetPropertyValues = {0}", string.Join(", ", props.Select(p => p.GetValue(userRole, null))));            string name = userRole.UserName;            Guid[] result = Enumerable.ToArray(userRole.RoleIds ?? new object[0]);            WriteArray(check, result);        }        private static void Write<T>(T check, T result) where T : class{            Console.WriteLine("> '{0}'", check == result);        }        private static void Write(int check, int result)        {            Console.WriteLine("> {0} == {1} = '{2}'", check, result, check == result);        }        private static void WriteArray<T>(T[] check, T[] result) where T : class{            for (int i = 0; i < check.Length; i++)            {                Console.WriteLine("> {0} : c={1}, r={2}  '{3}'", i, check[i], result[i], check[i] == result[i]);            }        }        private static void WriteArray(Guid[] check, Guid[] result)        {            for (int i = 0; i < check.Length; i++)            {                Console.WriteLine("> {0} : c={1}, r={2}  '{3}'", i, check[i], result[i], check[i] == result[i]);            }        }        private static void WriteArray(int[] check, int[] result)        {            for (int i = 0; i < check.Length; i++)            {                Console.WriteLine("> {0} : c={1}, r={2}  '{3}'", i, check[i], result[i], check[i] == result[i]);            }        }    }}

开源地址:

https://github.com/zzzprojects/System.Linq.Dynamic.Core

https://www.nuget.org/packages/System.Linq.Dynamic.Core

(0)

相关推荐

  • C# 改变Windows中服务的登录身份 (账户名和密码)

    在 C# 中,我们可以使用 WMI 类中的 Win32_Service 或者 Win32 API 中的函数 ChangeServiceConfig 来修改本地或远程计算机 Windows 服务登录身份 ...

  • C#队列学习笔记:RabbitMQ延迟队列

    一.引言 日常生活中,很多的APP都有延迟队列的影子.比如在手机淘宝上,经常遇到APP派发的限时消费红包,一般有几个小时或24小时不等.假如在红包倒计时的过程中,没有消费掉红包的话,红包会自动失效.假 ...

  • 都2020年了,你还在掉这些“坑”吗?3分钟教会你如何挑选数据线

    现在电商平台已经很少能够看到假冒伪劣的数据线产品出现了,只要选择在大型电商平台的品牌商家进行选购就很难买到劣质产品,当然还是不推荐购买线上不明卖家或者是线下"地摊"销售的" ...

  • 都2020年了,为什么还在用iPhone 5S?

    有的同事依然在抱着iPhone 5s在用,什么心态?以前遇到的同事依然抱着iPhone 5s在用,但当时iPhone 8都已经出了,是怀念乔布斯的缘故吗? 其实只要够用就行,iPhone5S的配置来说 ...

  • 都2020年了,拍照还用剪刀手这种老掉牙的pose太out啦

    注:本文转载自网络,不代表本平台立场 相信爱美的女生都爱拍照,但拍照姿势是非常重要的,姿势不正确很容易尴尬,拍出来效果也不尽人意. 很多女生在拍照时,并不喜欢太刻意的摆拍,尤其是镜头感是很强的女生更是 ...

  • 「古今对比」都2020年了,你还搞不懂铁杆怎么选?!

    想了解你自己的铁杆属于什么类型吗?想了解自己适合什么类型的铁杆吗? 今天,高烧研究所所长Jason就要给大家测评一根超过50年历史的古董铁杆!并且会通过现代球杆与古董球杆的对比,给大家详细讲解铁杆杆头 ...

  • 都2020年了,为什么还有人怀念iPhone SE

    众所周知,2020年是行业公认的"5G普及年".在年初,一大批外观精致.性能强大.显示效果惊艳.技术完善的5G旗舰机型闪亮登场,充分展示了5G在顶级设备上的魅力.而当时间接近年中时 ...

  • 都2020年了,居然还有人觉得买苹果电脑是“有钱人”

    都2020年了,居然还有人认为买苹果是富有的象征.被知乎上的一个回答气到了,他说:那些买了苹果MacBook,又骂不实用的人,其实本质上是因为贫穷? 我在这里不针对答主,只是反对这种用「贫富差距」来解 ...

  • 都2020年了, 你还认为孩子的问题是父母造成的吗?

    最近看了<雷霆战将><八佰><金刚川><战火熔炉>这几部电影.这其中值得看第2遍的只有<战火熔炉>. 电影拍的不好,观众的情绪就得不到宣泄和 ...

  • 都2020年了,你还这样看壶吗?

    一般情况下,我们去买紫砂壶,首先考虑价格预算.喜欢的壶型泥料.哪个老师做的.适合泡什么茶,还有看这把壶出水是否顺畅.是不是会漏水等. 而是否会漏水一般说的就是紫砂壶的气密性.气密性是众多壶友在购买紫砂 ...

  • 都2020年了,你还不懂5G

    如何感受5G?当5G手机连接上5G信号,5G高带宽特性能在十几秒的时间内下载一个大小超过1G的<王者荣耀>.快,是最直接的感受:而5G的低时延特性,则在与家人亲友无卡顿实时视频聊天中呈现. ...