我有两个sql表Department和Lecturer:
Department: DepartmentID, Name
Lecturer: LecturerID, Name, DepartmentID
我想在列表中显示数据:
Lecturer ID, Name and Department Name
如何使用Linq to Sql(有或没有lambda表达式)实现这一点?我非常感谢你的帮助。谢谢。
答案 0 :(得分:1)
您需要使用Department表和Lecturer表之间的连接
DataClassesDataContext tdc = new DataClassesDataContext();
var res = (from p in tdc.Lecturers
join br in tdc.Departments on p.DepartmentID equals br.DepartmentID
select new
{
p.DepartmentID,
p.Name,
lectID = p.DepartmentID,
depname = br.Name
}
).ToList();
你的查询将是这样的
答案 1 :(得分:0)
感谢您的回答singhm0077。我很少与 join 混淆,不幸的是它没有像我想的那样工作。幸运的是,我找到了另一种解决方案。
由于表讲师中没有列 DepartmentName ,我必须创建 Lecturer 表的部分类,因为我是要绑定来自 Lecturer 表的数据,我定义了一个属性 DepartmentName ,它在数据库表中添加了一列。
public partial class Lecturer
{
public string DepartmentName
{
get;
set;
}
}
设计部分是:
<ext:GridPanel ID="grid1" runat="server" Width="600px" Header="false">
<Store>
<ext:Store ID="store1" runat="server">
<Model>
<ext:Model ID="model1" runat="server">
<Fields>
<ext:ModelField Name="LecturerID" Type="Int" />
<ext:ModelField Name="Name" Type="String" />
<ext:ModelField Name="DepartmentName" Type="String" />
</Fields>
</ext:Model>
</Model>
</ext:Store>
</Store>
<ColumnModel>
<Columns>
<ext:Column ID="colLecturerID" runat="server" Flex="1" DataIndex="LecturerID" Text="Lecturer ID"></ext:Column>
<ext:Column ID="colName" runat="server" Flex="1" DataIndex="Name" Text="Name"></ext:Column>
<ext:Column ID="colDepartmentName" runat="server" Flex="1" DataIndex="DepartmentName" Text="Department Name"></ext:Column>
</Columns>
</ColumnModel>
</ext:GridPanel>
使用linq2sql,部分代码是:
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
this.store1.DataSource = GetDataToBind();
this.store1.DataBind();
}
}
private List<Lecturer> GetDataToBind()
{
DataBaseDataContext db = new DataBaseDataContext();
List<Lecturer> lstLecturers = db.Lecturers.OrderBy(x => x.LecturerID).ToList();
foreach (Lecturer lecturer in lstLecturers)
{
lecturer.DepartmentName = lecturer.Department.Name;
}
return lstLecturers;
}
最后,如果数据库如下:
输出如下所示:
尽管如此,我不知道它是不是最好的方法。但是,它一直在工作。