我已经被linq query
困住了很长一段时间,而且无法弄清楚如何解决它。
I have this many-to-many relationship
课程类:
public class Course : BaseEntity
{
public Course()
{
CourseCollections = new HashSet<CourseCollection>();
}
public int Id { get; set; }
public string Name { get; set; }
public int CompanyId { get; set; }
public virtual ICollection<CourseCollection> CourseCollections { get; set; }
}
CourseCollection类:
public class CourseCollection
{
public CourseCollection()
{
Courses = new HashSet<Course>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
public virtual Company Company { get; set; }
public int CompanyId { get; set; }
}
我想做的是,通过提供collectionId
和companyId
,返回一个CourseCollection
对象,并将所有归属课程添加到列表中的集合中。
例如,如果我有3个属于集合1的课程,2个属于集合2的课程,我希望能够查询集合1并返回带有ICollection
内的3个课程的集合。 / p>
到目前为止我尝试了什么:
var group = _context.CourseCollections.GroupJoin(_context.Courses,
collection => collection.Id,
course => course.CompanyId,
(collection, courses) =>
new
{
Id = collection.Id,
CompanyId = collection.CompanyId,
Name = collection.Name,
Courses = courses
}
).AsQueryable();
但是这不起作用 - (并且它不应该工作,因为没有正确查询Courses表)。我只是想不通怎么做......
答案 0 :(得分:1)
使用&#34;选择&#34;尝试使用匿名类型进行投影(适用于急切或懒惰的加载):
var group = _context.CourseCollections
.Select(x => new {x.Id,
x.CompanyId,
x.Name,
x.Courses})
.ToList();