我想通过映射数组中的列名来将LinQ查询写入数据库。
我在数组
中有以下列名string[] myColumns = {"CustID","FirstName","LastName","OrderID" };
客户模型具有以下属性
public class Customer
{
public int CustID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
我无法使用LinQ将列映射到Customer表。我尝试将代码实现如下代码,但我没有得到结果。
var myResult=db.Customers.Select(x=>
new
{
myColumns[0]=x.CustID,
myColumns[1]=x.FirstName,
myColumns[2]=x.LastNmae
}).ToList();
我感谢您的帮助
答案 0 :(得分:0)
基于此讨论How to add dynamic member name and value to an instance of ExpandoObject class?我找到了解决问题的方法,使用以下方法可以为动态成员提供价值
public static List<ExpandoObject> MapColumnsAndGetResult<T>(List<T> YourDataInList, string[] ColumnNames)
{
var result = new List<ExpandoObject>();
foreach (var objClass in YourDataInList)
{
if (objClass != null)
{
var dynamicClass = new ExpandoObject() as IDictionary<string,object>;
foreach (var prop in objClass.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (ColumnNames.Contains(prop.Name))
{
dynamicClass.Add(prop.Name, prop.GetValue(objClass, null));
result.Add((ExpandoObject)dynamicClass);
}
}
}
}
result = result.Distinct().ToList();
return result;
}
如何使用:
var dataModel = db.ChapterRepository.GetAll().ToList();
var myResult = MapColumnsAndGetResult(dataModel, myColumns);
foreach (var x in myResult)
{
foreach (var property in (IDictionary<String, Object>)x)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
}