简体   繁体   中英

How to add to junction table of many-to-many relationship in MVC?

I am having trouble adding to and accessing the junction table in my MVC project. Currently, I have a class of ApplicationUsers which is stored in the AspNetUsers default table. Additionally, I have a class of Projects which is stored in a respective table. Users can have multiple projects, and projects can have multiple users. I can't access the junction table from my controller, nor can I do something like: db.Projects.Users.add(...) without getting an error message that DbSet does not contain a definition for Users.

Here is my ApplicationUser class:

using System;
using System.Security.Claims;
using IssueTracker.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;

namespace IssueTracker.Areas.Identity.Data
{
   public class ApplicationUser : IdentityUser
   {
       public ApplicationUser()
       {
           this.Projects = new HashSet<ProjectModel>();
       }

       public String? FirstName { get; set; }

       public String? LastName { get; set; }

       public String? Role { get; set; }

       public virtual ICollection<ProjectModel> Projects { get; set; }
   }
}

and here is my Projects class:

using System;
using Microsoft.AspNetCore.Identity;
using IssueTracker.Areas.Identity.Data;
using System.ComponentModel.DataAnnotations;

namespace IssueTracker.Models
{
    public class ProjectModel
    {
        public ProjectModel()
        {
            this.Users = new HashSet<ApplicationUser>();
        }

        public int Id { get; set; }

        public string? Name { get; set; }

        public string? Description { get; set; }

        public string? Status { get; set; }

        public string? ClientCompany { get; set; }

        public string? ProjectLeader { get; set; }

        public ICollection<ApplicationUser> Users { get; set; }

    }
}

This is my DbContext:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using IssueTracker.Models;

namespace IssueTracker.Areas.Identity.Data;

public class IssueTrackerIdentityDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<ProjectModel> Projects { get; set; }

    public IssueTrackerIdentityDbContext()
    {

    }

    public IssueTrackerIdentityDbContext(DbContextOptions<IssueTrackerIdentityDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        builder.ApplyConfiguration(new ApplicationUserEntityConfiguration());

        builder.Entity<ProjectModel>()
                .HasMany<ApplicationUser>(s => s.Users)
                .WithMany(c => c.Projects);
    }


}

public class ApplicationUserEntityConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
    public void Configure(EntityTypeBuilder<ApplicationUser> builder)
    {
        builder.Property(u => u.FirstName).HasMaxLength(255);
        builder.Property(u => u.LastName).HasMaxLength(255);
    }
}

and lastly, here is my controller where I am getting the error message:

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using IssueTracker.Models;
using Microsoft.AspNetCore.Authorization;
using IssueTracker.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace IssueTracker.Controllers;

[Authorize]
public class HomeController : Controller
{
    private IssueTrackerIdentityDbContext db;
    private UserManager<ApplicationUser> userManager;
    private RoleManager<IdentityRole> roleManager;

    public HomeController(IssueTrackerIdentityDbContext db, UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager)
    {
        this.db = db;
        this.userManager = userManager;
        this.roleManager = roleManager;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult CreateProject()
    {
        return View();
    }

    [HttpPost]
    public IActionResult CreateProject(String Name, String Description, String Status,
        String ClientCompany, String ProjectLeader, List<string> Contributors)
    {
        var project = new ProjectModel
        {
            Name = Name,
            Description = Description,
            Status = Status,
            ClientCompany = ClientCompany,
            ProjectLeader = ProjectLeader
        };

        db.Projects.Add(project);
        db.Projects.Users.Add(ProjectLeader);
        return View();
    }

}


I am not sure how to add to the junction table to properly link users to projects. Please let me know if there is something wrong with my setup of the many-to-many relationship or if there is a way to fix the error message. Thank you!!

You can try the code like below:

 var project = new ProjectModel
        {
            Name = Name,
            Description = Description,
            Status = Status,
            ClientCompany = ClientCompany,
            ProjectLeader = ProjectLeader
        };

    //db.Projects.Add(project);
   // db.Projects.Users.Add(ProjectLeader);
      var User = new ApplicationUser()
        {
            FirstName="a"
        };
        project.Users.Add(User);
        db.Projects.Add(project);

Read this answer to know more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM