Base solution for your next web application
Open Closed

Many to many relationship #11154


User avatar
0
Pablo created

Hello,

I'm trying to create a many to many relationship.

I would appreciate it if I can be given an example on how to create the DTO objects for Selecting, Editing, Inserting.

I got this far when trying to retrieve data:

            var project = await _projectRepository
                           .GetAll()
                           .Include(p => p.Type)
                           .Include(p => p.Project_Users)
                           .OrderBy(p => p.Id)
                           .ThenBy(p => p.Name)
                           .FirstOrDefaultAsync(x => x.Id == input.Id.Value);
                           

Project_Users is mapped to the Join table.

This is partially working but I can't get the values of the joint table.

I need to get all users releted to a particular project. I tried with this approach but I didn't work:

var project = await _projectRepository .GetAll() .Include(p => p.Type) .Include(p => p.Client) .Include(p => p.Users) .OrderBy(p => p.Id) .ThenBy(p => p.Name) .FirstOrDefaultAsync(x => x.Id == input.Id.Value);

I found this old post which is pretting much what I need, but the file link with examples they talk about is missing: https://support.aspnetzero.com/QA/Questions/9684/Many-to-many-DTO-example-needed

I would appreciate it if I can be refered to an up-to-date example of this senario.


1 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @Pablo

    We don't have a complete sample because it is similar to how you can do it with a regular EF Core project but we will consider preparing a sample tutorial for this case.

    I think you can use .ThenInclude after .Include(p => p.Project_Users) to include users.

    Something like this should work;

    .Include(p => p.Project_Users)
    .ThenInclude(p=> p.Users)