简体   繁体   English

如何在MVC中添加多对多关系的联结表?

[英]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.我在 MVC 项目中添加和访问联结表时遇到问题。 Currently, I have a class of ApplicationUsers which is stored in the AspNetUsers default table.目前,我有一个 ApplicationUsers 的 class 存储在 AspNetUsers 默认表中。 Additionally, I have a class of Projects which is stored in a respective table.此外,我有一个项目的 class 存储在相应的表中。 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.我无法从 controller 访问联结表,也无法执行以下操作: db.Projects.Users.add(...)而不会收到 DbSet 不包含用户定义的错误消息。

Here is my ApplicationUser class:这是我的 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:这是我的项目 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:这是我的 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:最后,这是我收到错误消息的 controller :

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.阅读此答案以了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在多对多关系中映射查找/连接表实体 - Mapping lookup/junction table entity in many-to-many relationship EntityFramework与联结表多对多 - EntityFramework many-to-many with junction table 为实体框架中的多对多关系禁用隐式创建的联结表 - Disabling the Implicitly created junction table for many-to-many relationship in Entity Framework ASP .NET Core MVC Entity Framework - 如何访问由多对多关系产生的表? - ASP .NET Core MVC Entity Framework - How to get access to a table which is result of many-to-many relationship? 如何与自定义 ApplicationUser class MVC 创建多对多关系? - How to create many-to-many relationship with custom ApplicationUser class MVC? mvc和EF中的多对多关系 - many-to-many relationship in mvc and EF 多对多 Entity Framework Core 6(未生成联结表) - Many-to-Many Entity Framework Core 6 (junction table not generated) CheckboxList,MVC,多对多关系 - CheckboxList, MVC, Many-To-Many Relationship 如何在Entity Framework Core中将项目添加到多对多关系表中? - How to add an item to a many-to-many relationship table in Entity Framework Core? 实体框架,代码优先,如何从多对多关系映射中向表添加主键? - Entity Framework, code-first, how to add primary key to table out of many-to-many relationship mapping?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM