【问题标题】:Entity Framework Core Many-to-Many Implementation实体框架核心多对多实现
【发布时间】:2020-01-26 09:16:57
【问题描述】:

这么多对多没有进入 .NET Core 3.0 版本,真糟糕……

我知道如何使用连接实体实现 m:m,如下例所示:https://stackoverflow.com/a/53972658/980917

我的问题是关于模型类本身。以学生和班级为例:

Student - has ICollection<StudentClass> 

StudentClass - joining entity

Class - has ICollection<StudentClass> 

这对于数据加载来说很好。但是在您的 StudentClasses 业务逻辑集合中没有用,因为它只是一个具有 2 个 ID 的连接实体。当使用 StudentClass 时,您实际上需要 Student 中的 Classes 的实际集合和 Student 的集合班级内的strong>学生。 (即:Student.Classes & Class.Students

目前推荐的检索多对多集合(不加入实体)的方法/解决方法是什么?

我们是否必须根据加入实体进行第二次选择,还是有更优雅的方法?

一个简单的例子或一个链接会很棒。谢谢。

【问题讨论】:

  • What's the current recommended approach / workaround to populate those list when pulling data?- 最后一部分我不清楚。请你说清楚好吗?
  • 添加了更多细节。基本上,检索多对多实体的推荐方法是什么(不加入实体,因为它在业务逻辑中没有用处)。
  • 请检查我的回答。

标签: entity-framework .net-core entity-framework-core many-to-many ef-core-3.0


【解决方案1】:

目前推荐的检索多对多集合(不加入实体)的方法/解决方法是什么?

您可以使用.Include 扩展方法轻松完成如下:

假设您的Student 类如下:

public class Student
{
  public int Id {get; set;}
  public string StudentName {get; set;}

  public ICollection<StudentClass> StudentClasses {get; set;}
}

检索所有学生及其相关课程:

var studentsWithClasses = _context.Students.Include(s => s.StudentClasses).ToList();

要检索单个学生及其班级:

var studentWithClasses = _context.Students.Where(s => s.Id = studentId).Include(s => s.StudentClasses).FirstOrDefault();

【讨论】:

  • 感谢您的澄清。我最初担心的是,为了从 Student 访问 Classes,我必须使用 Student.StudentClasses.Classes,这很烦人。但我可以轻松地在其周围添加一个 Student.Classes 包装器属性,我想只是忽略公共加入实体集合。
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多