开发者

LINQ Entity Framework Select into a non-primary-key relationship

i have a 3 class models with overlapping relationships:

class worder {
  int workerID
}    
class shift {
  int shiftID,
  int workerID,
  ICollection tasks //tasks for this shift and this worker
}
class task {
  int workerID
  int shiftID
}    

how do i populate a collection of shift objects that include its respective .tasks? something like:

var q = from shi开发者_C百科ft in db.shifts
  .Include(s => s.tasks.Where(t=>t.shiftID == s.shiftID && t.workerID = s.workerID))

EDIT

I have successfully used an projection to create an anonymous type as suggested by jethro. but i would like to return strongly typed shift classes instead. is that possible? or a poor design of the shift model?


You can join the tables.

var joinedTables = from c in db.shifts
                   join p in db.tasks on c.ShiftID equals p.ShiftID & c.WorkerID equals p.WorkerID
select new {Shifts = c, Tasks = p };

Please check this Link for additional examples on Linq Joins.

var shifts = db.shifts;
var tasks = db.tasks;

foreach(var shift in shifts)
{
    var shiftID = shift.ShiftID;
    var workerID = shift.WorkerID;
    shift.tasks = tasks.Where(p=>p.shiftID == shiftID & p.WorkerID == workerID);
}

Something about the above feels "not right" to me, I think it would be best if you look at your design again, the tasks of the shifts should be populated automatically when you pull the shifts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜