linq to entities - Entity framework Many-to-Many relations -
i trying find way make collection of entities (something this):
students: | studentid | name | ------------------------- | 1 | joe | | 2 | jack | studentscourses: | studentid | courseid | ------------------------- | 1 | 1 | | 2 | 1 | | 2 | 2 | courses: | courseid | name | --------------------------- | 1 | math | | 2 | math ii |
into ienumerable of this:
class studentdto { public int id {get; set;} public string name {get; set;} public list<coursedto> courses {get; set;} } class coursedto { public int id {get; set;} public string name {get; set;} }
using linq , ef in c#. have been looking @ groupby() method cannot see how make "fit" needs. hints or suggestions appreciated.
so far have follwing query:
var result = s in db.students sc in db.studentscourses.where(x => x.studentid == sc.studentid) c in db.courses.where(x => x.courseid == sc.courseid) select new studentdto() { id = s.studentid, name = s.name courses = ??? };
how can make list out of courses on each student?
you should move 2 from
s select
:
from s in db.students select new studentdto() { id = s.studentid, name = s.name courses = sc in db.studentscourses .where(x => x.studentid == s.studentid) c in db.courses.where(x => x.courseid == sc.courseid) select new coursedto { id = c.id, name = c.name } };
however, recommended have navigation properties in classes: @ least student.studentcourses
, studentcourse.course
. can do:
from s in db.students select new studentdto() { id = s.studentid, name = s.name courses = sc s.studentscourses select new coursedto { id = sc.course.id, name = sc.course.name } };
Comments
Post a Comment