利用SqlQuery实现动态查询

public static IEnumerable<dynamic> SqlQueryDynamic(this DbContext db, string Sql, params SqlParameter[] parameters)
        {
            using (var cmd = db.Database.Connection.CreateCommand())
            {
                cmd.CommandText = Sql;

                if (cmd.Connection.State != ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }

                foreach (var p in parameters)
                {
                    var dbParameter = cmd.CreateParameter();
                    dbParameter.DbType = p.DbType;
                    dbParameter.ParameterName = p.ParameterName;
                    dbParameter.Value = p.Value;
                    cmd.Parameters.Add(dbParameter);
                }

                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        var row = new ExpandoObject() as IDictionary<string, object>;
                        for (var fieldCount = 0; fieldCount < dataReader.FieldCount; fieldCount++)
                        {
                            row.Add(dataReader.GetName(fieldCount), dataReader[fieldCount]);
                        }
                        yield return row;
                    }
                }
            }
        }
复制代码

那么最终如上查询后返回动态集合,我们该如何转换为集合对象呢?我想都没想如下直接先序列化然后反序列化,若您有更好的解决方案,请自行实现即可。

复制代码
            using (var ctx = new EfDbContext())
            {
                ctx.Database.Log = Console.WriteLine;

                var dynamicOrders = ctx.SqlQueryDynamic("select * from dbo.Orders");
                var ordersJson = JsonConvert.SerializeObject(dynamicOrders);
                var orders = JsonConvert.DeserializeObject<List<Order>>(ordersJson);
            };

若有多个表也是好使的,最后反序列化为不同的对象即可

 

posted on 2018-07-31 15:45  无爱无伤  阅读(509)  评论(0编辑  收藏  举报