linq to sql返回动态表 [英] linq to sql return dynamic table
问题描述
Hi, 我希望像使用ADO一样使用linq来执行sql并返回动态表,就像我使用数据表一样。 I am looking to use linq to sql like I did with ADO and return a dynamic table like I did with a datatable. I我不知道在运行之前会返回哪些表/字段。 我后来想循环遍历返回表并获取字段名称和值。 I will not know what table/fields will return until runtime. I later want to loop through the return table and get the field names and values. 如果这是一个数据表,它看起来像 if this was a datatable it would look something like System.Data。 System.Data. DataTable DataTable
dt = new
DataTable();
foreach foreach
(DataRow
dr in
dt.Rows ) { string string
fieldName = dt.Columns[0].ColumnName;
string string
values = dr[0].ToString(); } 这是我的linq to sql但动态不起作用 Here is my linq to sql but dynamic will not work var var
recordSet = (db.ExecuteQuery<dynamic>(sql,
"")); 据我所知,你似乎无法做到这一点框。 From my knowledge it looks like you cannot do that out of the box. 你可以使用DataContext.GetTable来获得ITable或表< TEntity>,但需要输入的行返回。 You can use DataContext.GetTable to get ITable or Table<TEntity>, but the rows returned from those need to be typed. 如果您有一个表中的对象列表,您可以编写一个搜索属性的反射方法属性[Column], 并把它放入一个List(就像这样)。 If you had a list of objects from a table, you could write a reflective method that searches for properties with the attribute [Column], and put that into an List (like so). 这篇关于linq to sql返回动态表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
dt = new
DataTable ();
( DataRow
dr
dt.Rows)
fieldName = dt.Columns [0] .ColumnName;
values = dr [0] .ToString();
recordSet =(db.ExecuteQuery< 动态 >(sql,
" " )); 推荐答案
//Of course this off the top of my head. There maybe bugs.
//Make sure nulls are not skipped.
public List<object> GetColumns(object row)
{
List<object> results = new List<object>();
List<PropertyInfo> properties = ( from x in row.GetType().GetProperties() where x.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).Count() > 0
where x.CanRead
select x ).ToList();
foreach ( PropertyInfo property in properties )
{
object val = property.GetGetMethod().Invoke(row, null);
results.Add(val);
}
return results;
}