我正在尝试使用linq或entityframework将两个连接表的结果绑定到我的gridview中 我有
EmployeeData_Main Table (MainID, FirstName , SecondName ,LastName , DateOfBirth)
EmployeeData_Sub Table (SubID ,Address,Email,Tele,MainID-FK-)
我正在使用此查询绑定:
var queryResult = (from maindata
in db.EmployeeData_Main
join subData in db.EmployeeData_Sub
on maindata.MainID equals subData.MainID
select new
{
EmployeeData_Main = maindata,
EmployeeData_Sub = subData
})
.ToList();
GV.DataSource = queryResult;
GV.DataBind();
我使用EmployeeData_Main.FirstName
等绑定字段,但是出现了这个例外:
DataBinding: '<>f__AnonymousType0`2[[HR.EmployeeData_Main, HR, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],
[HR.EmployeeData_Sub, HR, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not contain a property with the name 'MainID'.
我读了一些话题
How can I bind a query with a join to a GridView, with a Linq datasource with a business layer and data access layer
&安培;
binding linq query result to gridview
但是我仍然得到同样的例外。如何成功绑定结果
答案 0 :(得分:1)
您的列表是匿名类型列表,仅包含两个属性:EmployeeData_Main
和EmployeeData_Sub
。
然后,要绑定的属性是EmployeeData_Main.MainID
,它不是匿名类型的直接属性。所以你的绑定不起作用。
我不知道您是否使用了来自WebForms或WPF的GridView
,但是在WPF中,您可以这样绑定它:
{ EmployeeData_Main.MainID }
或者您可以用匿名类型选择您的财产:
var queryResult = (from maindata in db.EmployeeData_Main
join subData in db.EmployeeData_Sub
on maindata.MainID equals subData.MainID
select new { MainID = maindata.MainID, EmployeeData_Main = maindata, EmployeeData_Sub = subData })
.ToList();
答案 1 :(得分:0)
似乎网格正在尝试查找属性queryResult.MainID
,而应该查找queryResult.EmployeeData_Main.MainID
。我不知道这是否真的可行。
您可以专门声明要选择的字段:
var queryResult = (from maindata in db.EmployeeData_Main
join subData in db.EmployeeData_Sub on maindata.MainID equals subData.MainID
select new {
maindata.MainID,
maindata.FirstName ,
maindata.SecondName ,
maindata.LastName ,
maindata.DateOfBirth,
subData.SubID ,
subData.Address,
subData.Email,
subData.Tele,
subData.MainID-FK-
}).ToList();