I have 3 tables with a many to many relationship between them
User: Id (PK), Name
UserCourses: UserId (PK), CourseId (PK)
Courses: Id (PK), Name
I need to write a linq query to select all the courses name of user X and return in a IEnumerable but I can’t get it to work.
EDIT:
public IEnumerable<Courses> GetCourses
{
get
{
return (from a in _entities.Users.Include("Courses")
where a.Id == this.Id
select a.Courses.AsEnumerable()
);
}
}
Any help much appreciated
Thanks
You’re a little unclear about what’s going wrong, but that looks like it would produce an
IEnumerable<IEnumerable<Courses>>type. If you’re looking for a flattenedIEnumerable<Courses>, which I think you are, you need something like:EDIT: To avoid a NullReferenceException, try this instead:
Note that there are more than one ways to do this; for example, you could also use:
If the
SelectManyversion still causes a NullReferenceException, use this instead. I don’t think it should, but I haven’t tested it. You indicated that Rup’s solution had done that, and he’s usingSelectManyin much the same way I am, so this last version plays it safe.