我正在升级一个旧程序,并使用linq进行基本选择,以便我可以在过程中学习linq。我有一个重复的任务,只是显示数据从各种连接是网格视图,下面是一个示例
protected void Page_Load(object sender, EventArgs e)
{
using ( vavestockModel.vavestockEntities db = new vavestockModel.vavestockEntities())
{
var prod = (from p in db.products select p);
var prodd = (from p in db.productdetails select p);
var prode = (from p in db.product_extra_data select p);
var join1 = (from p in prod
join
pd in prodd
on p.PrStyle equals pd.StyleCode
select new {pr=p,prd=pd }).ToList();
var join2 = (from p in prod
join
pd in prodd
on p.PrStyle equals pd.StyleCode
select new { p.PrShow,p.PrPrice,pd.I_EAN_51,pd.I_EAN_50 }).ToList();
var join3 = (from p in prod
join
pd in prodd
on p.PrStyle equals pd.StyleCode
select new { flattenmodel(p),flattenmodel(pd) }).ToList();
Response.Write(join1);
GridView1.DataSource = join1;
GridView1.DataBind();
}
}
??object flattenmodel(vavestockModel.vavestockEntities en)//? here i want to pass any table row
{
string[] toren;
//foreach (var item in en.)
//{
//}
return toren;
}
join2可以绑定到gridview,而join1不能,因为它们返回实体对象。因为我必须为这么多表选择所有列,重复编写所有名称不是明智的选择,因此我想编写一个返回扁平数据的函数。
但是我发现很难继续下去。我的困难来了,因为我不知道在这种情况下应该返回什么作为参数传递。谁能给我指出正确的方向吗?
您可以通过System.Reflection
获得对象的所有属性,这里有一个示例,您可以从所有属性中获取值并将它们存储在List
中,然后您可以将此List
指定为数据源。
Entities ent = new Entities();
var data = (from x in ent.Employees where x.Id == 1 select x).FirstOrDefault();
List<string> list = ConvertToList(data);
public List<string> ConvertToList(object obj)
{
List<string> list = new List<string>();
PropertyInfo[] pinfo = obj.GetType().GetProperties();
foreach (var info in pinfo)
{
if (info.GetValue(obj) != null)
list.Add(info.GetValue(obj, null).ToString());
}
return list;
}
编辑
您也可以从匿名对象返回DataTable
。
public DataTable ConvertToDataTable(IEnumerable<dynamic> obj)
{
DataTable dt = new DataTable();
foreach (dynamic item in obj)
{
DataRow dr = dt.NewRow();
PropertyInfo[] pinfo = item.GetType().GetProperties();
foreach (var info in pinfo)
{
if (!dt.Columns.Contains(info.Name))
dt.Columns.Add(info.Name, info.PropertyType);
var val= info.GetValue(item, null);
dr[info.Name] = val;
}
dt.Rows.Add(dr);
}
return dt;
}
你可以这样调用它
Entities ent = new Entities();
var data = (from x in ent.Employees where x.Id == 1 select x).FirstOrDefault();
DataTable dt=ConvertToDataTable(data);