目前存在字段可配置的动态需求,因此数据表的字段和类型都是未知的,又需要取出具体的字段名和值返回给前端,所以使用dynamic (System.Dynamic.ExpandoObject)动态对象来实现 。
//查询的sql
string sql = "SELECT * FROM `eass`.`order_node_active_field` WHERE orderDetailId = '" + orderdetailid + "';";
var orderNodeActiveFieldData = dbContext.Database.SqlQuery(sql);
int rows = orderNodeActiveFieldData.Rows.Count;
//返回给前端的数据集合
List<object> myDataList = new List<object>();
for (int i = 0; i < rows; i++)
{
dynamic myData = new System.Dynamic.ExpandoObject();
//创建属性并赋值
foreach (DataColumn cl in orderNodeActiveFieldData.Columns)
{
var data = orderNodeActiveFieldData.Rows[i][cl.ColumnName];
switch (cl.DataType.Name)
{
//涉及到DateTime需要单独处理一下,或者有其他需求也可以在这里加
case "DateTime":
(myData as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new System.Collections.Generic.KeyValuePair<string, object>(cl.ColumnName, data.ToString() != "" ? (DateTime)data : null));
break;
default:
(myData as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new System.Collections.Generic.KeyValuePair<string, object>(cl.ColumnName, data));
break;
}
}
myDataList.Add(myData);
}
数据集结果如下: