我有3个表:
- Users:(Id, FirstName, LastName, DepartmentId, LocationId)
- Departments:(Id, DepartmentName)
- Locations: (Id, LocationName)
如何使用lambda表达式将Department.Id
连接到User.DepartmentId
和Location.Id
连接到User.LocationId
?
我被卡住了目前与1连接。我试着去研究这个问题,但是我看到的结果与多对多的关系有关。
var userJoin = _db.Users
.Join(_db.Departments,
user => user.DepartmentId,
dept=> dept.Id,
(l, r) => new { l, r })
.Select(m => new UserModel()
{
// Map
}).ToList();
您有几个选择:
使用导航属性。它会更简单,看起来像这样
context.Users.Include(x=>x.Department)
.Include(x=>x.Location)
.ToList()
使用加入
context.Users.Join(context.Departments, x=>x.DepartmentId, x=>x.Id, (user, department) => new
{
User = user,
Department = department
})
.Join(context.Locations, x=>x.User.LocationId, x=>x.Id, (userDepartment, location) => new
{
User = userDepartment.User,
Department = userDepartment.Department,
Location = location
})
.ToList()