(LINQ 学习系列)(7)Linq教程实例: LINQ多表关联操作
1.建立2个关系表,分别是student, class表. 学生与课程表. 如下图所示例
2. 在vs2010 中新建窗体.
namespace LinqTest
{
public partial class FrmManyToMany : Form
{
internal static string sqlconStr = @"Data Source=localhost;Initial Catalog=lxPower;user=sa;pwd= ";
public FrmManyToMany()
{
InitializeComponent();
}
private void FrmManyToMany_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
DataClasses1DataContext db = new DataClasses1DataContext(sqlconStr);
var q = from c in db.student
join o in db.Oclass on c.StudentName equals o.StudentName
select new { c.ID, c.StudentName, o.Class };
this.dataGridView1.DataSource = q;
}
}
}
{
public partial class FrmManyToMany : Form
{
internal static string sqlconStr = @"Data Source=localhost;Initial Catalog=lxPower;user=sa;pwd= ";
public FrmManyToMany()
{
InitializeComponent();
}
private void FrmManyToMany_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
DataClasses1DataContext db = new DataClasses1DataContext(sqlconStr);
var q = from c in db.student
join o in db.Oclass on c.StudentName equals o.StudentName
select new { c.ID, c.StudentName, o.Class };
this.dataGridView1.DataSource = q;
}
}
}
在这里使用了LINQ To SQL语句,其实你可以使用DataContent做关系的.
运行结果如下图:
2个表的关系是不是非常简单,在实际操作中可能会遇到很多问题,我们可以一起探讨以下
原创作品,转载请注明出处!!!