Home > Software engineering >  Many to Many relation for ApplicationUser and Custom model class
Many to Many relation for ApplicationUser and Custom model class

Time:12-08

I am trying to implement following case scenario: There is a custom table, let's say Task and I would like to create Many to Many relation with class Application user.

Currently I have following project arcitechture:

- Client
- Server
   - ApplicationUser.cs
- Shared
   - Task.cs

Here are classes:

Task.cs in Shared assembly:

public class Task
{      
    public Guid Id { get; set; }
    public string Name { get; set; }

    public ICollection<ApplicationUser> ApplicationUsers { get; set; }    
    public List<ApplicationUserTask> ApplicationUserTasks { get; set; }
}

ApplicationUser.cs in Server assembly:

public class ApplicationUser : IdentityUser
{
    public Guid Id { get; set; }

    public ICollection<Task> Tasks { get; set; }    
    public List<ApplicationUserTask> ApplicationUserTasks { get; set; }
}

According to Microsoft docs I need to create a new class called something like:

public class ApplicationUserTask
{      
    public int ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }

    public int TaskId { get; set; }
    public Task Task { get; set; }
}

There are references for Shared assembly in Client and Server. However due to current structure it is not possible to have such a relation and I need to move ApplicationUser.cs class to Shared assembly, but then I am getting conflict with NuGet packages, because of this one using Microsoft.AspNetCore.Identity;

What should I do?

  1. Create new class in Shared assembly? For example UserModel.cs and operate with this one? In this case there would be new table in DB. Should I constantly copy ApplicationUser table to UserModel table then?
  2. Move Task.cs to Server assembly do all procedures according to Microsoft documentation and then create TaskDTO.cs to Shared assembly and communicate with Client through DTO model?
  3. Some other better option?

I am using: <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />

CodePudding user response:

What should I do?

Option 2) is the best, imho.

IdentityUser belongs to a closed library that you don't want to reference in your client. It also contains a lot of fields that you don't need or want to expose in your API.

Your problem comes from an attempt to combine Model and DTO classes. That is not a best practice, although I admit it can be attractive in a (very) small app.

So keep your Models in the Server project and put tailor made DTO classes in Shared. Right now it is only essential for the User class but when your project grows you will be glad you did it for the rest too.

  • Related