Entity Framework 核心多对多实现
Entity Framework Core Many-to-Many Implementation
如此多对多并没有进入 .NET Core 3.0 版本,可惜...
我知道如何使用此示例中的连接实体实现 m:m:
我的问题是关于模型 类 本身的。考虑 Student & Class 示例:
Student - has ICollection<StudentClass>
StudentClass - joining entity
Class - has ICollection<StudentClass>
这对于数据加载目的来说很好。但是在您的业务逻辑集合中,StudentClasses 没有用,因为它只是一个具有 2 个 ID 的连接实体。在使用 Student 或 Class 时,您实际上想要 Classes[= Student 中的 35=] 和 Class 中的 Students 集合。 (即:Student.Classes & Class.Students。
目前推荐的检索多对多集合(不加入实体)的方法/解决方法是什么?
我们是否必须根据加入实体进行第二次 select 还是有更优雅的方法?
一个简单的例子或 link 会很棒。谢谢
What's the current recommended approach / workaround to retrieve the many-to-many collections (not joining entity)?
您可以使用 .Include
扩展方法轻松完成,如下所示:
假设您的 Student
class 如下:
public class Student
{
public int Id {get; set;}
public string StudentName {get; set;}
public ICollection<StudentClass> StudentClasses {get; set;}
}
检索所有学生及其关联的 classes:
var studentsWithClasses = _context.Students.Include(s => s.StudentClasses).ToList();
检索单个学生及其 classes:
var studentWithClasses = _context.Students.Where(s => s.Id = studentId).Include(s => s.StudentClasses).FirstOrDefault();
如此多对多并没有进入 .NET Core 3.0 版本,可惜...
我知道如何使用此示例中的连接实体实现 m:m:
我的问题是关于模型 类 本身的。考虑 Student & Class 示例:
Student - has ICollection<StudentClass>
StudentClass - joining entity
Class - has ICollection<StudentClass>
这对于数据加载目的来说很好。但是在您的业务逻辑集合中,StudentClasses 没有用,因为它只是一个具有 2 个 ID 的连接实体。在使用 Student 或 Class 时,您实际上想要 Classes[= Student 中的 35=] 和 Class 中的 Students 集合。 (即:Student.Classes & Class.Students。
目前推荐的检索多对多集合(不加入实体)的方法/解决方法是什么?
我们是否必须根据加入实体进行第二次 select 还是有更优雅的方法?
一个简单的例子或 link 会很棒。谢谢
What's the current recommended approach / workaround to retrieve the many-to-many collections (not joining entity)?
您可以使用 .Include
扩展方法轻松完成,如下所示:
假设您的 Student
class 如下:
public class Student
{
public int Id {get; set;}
public string StudentName {get; set;}
public ICollection<StudentClass> StudentClasses {get; set;}
}
检索所有学生及其关联的 classes:
var studentsWithClasses = _context.Students.Include(s => s.StudentClasses).ToList();
检索单个学生及其 classes:
var studentWithClasses = _context.Students.Where(s => s.Id = studentId).Include(s => s.StudentClasses).FirstOrDefault();