linq to sql返回动态表 [英] linq to sql return dynamic table

查看:79
本文介绍了linq to sql返回动态表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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
dt =
new
DataTable ();

DataTable dt = new DataTable();

 

 

foreach
DataRow
dr

dt.Rows)

foreach (DataRow dr in dt.Rows )

{

 

 

string
fieldName = dt.Columns [0] .ColumnName;

string fieldName = dt.Columns[0].ColumnName;

 

 

string
values = dr [0] .ToString();

string values = dr[0].ToString();

}

这是我的linq to sql但动态不起作用

Here is my linq to sql but dynamic will not work

var
recordSet =(db.ExecuteQuery<
动态 >(sql,
" " ));

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).


//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;
}


这篇关于linq to sql返回动态表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆