C# Linq多对多、GroupJoin或SelectMany
我在一个C# Linq多对多、GroupJoin或SelectMany,c#,entity-framework,linq,C#,Entity Framework,Linq,我在一个linq查询上陷入了困境,已经有很长时间了,只是不知道如何解决它 课程类别: public class Course : BaseEntity { public Course() { CourseCollections = new HashSet<CourseCollection>(); } public int Id { get; set; } public string Name { get; set; }
linq查询上陷入了困境,已经有很长时间了,只是不知道如何解决它
课程类别:
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; }
}
但这不起作用-(并且它不应该起作用,因为课程表没有被正确查询)。我就是不知道怎么做…尝试使用“选择”将投影到匿名类型(适用于快速或延迟加载):
不需要GroupJoin
或SelectMany
。只需查询\u上下文。CourseCollections
(例如。其中(cc=>cc.Id==collectionId&&cc.CompanyId==CompanyId)
),EF惰性加载将为您完成其余的工作。或者使用即时加载通过单个数据库查询获取所有内容。我尝试了这种方法,但只返回了一个没有任何课程的对象:{“Company”:null,“courses”:[],“Id”:8,“Name”:“Collection 1”,“CompanyId”:1}
可能是延迟加载被禁用。然后使用第二个选项(即时加载),例如\u context.CourseCollections.Include(cc=>cc.Courses)。其中(…)
集合ID
不能唯一标识单个课程集合
?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; }
}
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();
var group = _context.CourseCollections
.Select(x => new {x.Id,
x.CompanyId,
x.Name,
x.Courses})
.ToList();