Entity Framework Core Many-to-Many Implementation

.net-core ef-core-3.0 entity-framework entity-framework-core many-to-many

Question

So Many-to-Many did not make it into .NET Core 3.0 release, bummer...

I'm aware of how to implement m:m using a join entity as in this example: https://stackoverflow.com/a/53972658/980917

My question is about the model classes themselves. Consider Student & Class example:

Student - has ICollection<StudentClass> 

StudentClass - joining entity

Class - has ICollection<StudentClass> 

That is fine for data loading purposes. But in your business logic collection of StudentClasses is not useful as its just a joining entity with 2 IDs. When working with Student or Class you actually want an actual collection of Classes inside a Student and a collection of Students inside a Class. (ie: Student.Classes & Class.Students.

What's the current recommended approach / workaround to retrieve the many-to-many collections (not joining entity)?

Do we have to do a 2nd select based on on the joining entity or is there something more elegant?

A quick example or a link would be great. Thanks.

1
0
9/27/2019 2:40:24 AM

Accepted Answer

What's the current recommended approach / workaround to retrieve the many-to-many collections (not joining entity)?

You can do easily with .Include extension method as follows:

Lets say your Student class as follows:

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

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

To retrieve all the students with their associated classes:

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

To retrieve a single student with its classes:

var studentWithClasses = _context.Students.Where(s => s.Id = studentId).Include(s => s.StudentClasses).FirstOrDefault();
1
9/27/2019 2:59:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow