LINQ中实现对象Many-To-Many(多对多)的关系映射
前段时间,大概用了一下LINQ to SQL, 发觉O/Rdesigner似乎没有Many-To-Many(多对多)关系的支持,只有自己写代码实现.
:(
提供一下俺的解决办法:
例如User和UserGroup的关系,假设保存在UserInGroups表中,这里记录了User和Group的对应关系,那么,需要手动在User/Group类中添加对应的partial属性:
public partial class User{
piblic IEnumerable<Groups> Groups
{
var groups = from g in db.UserInGroups
where g.UserId = this.UserId
select {g.Groups};
return groups;
}
}
public partial class Group{
piblic IEnumerable<Users> Users
{
var users = from u in db.UserInGroups
where u.GroupId = this.GroupId
select {u.Users};
return users;
}
}