entity-framework - Asp.Net MVC 5 中的多对多关系与身份表和自定义表

标签 entity-framework asp.net-mvc-5 ef-code-first foreign-keys entity-framework-6

我正在尝试在 Asp.Net Identity 生成的表中的用户与我自己的表之间建立关系。这种关系必须是多对多的,因为许多用户可以处理同一个任务(这是我的表),同时一个用户可以处理多个任务。

public class Task
{      
    public int ID { get; set; }
    public string Name { get; set; }

    public string UserID { get; set; }

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

public class ApplicationUser : IdentityUser
{
    public int TaskID { get; set; }
    public virtual ICollection<Task> Tasks{ get; set; }

    // rest of the code
}

我尝试过这种方式,但在迁移(或运行时)期间出现错误

“在模型生成过程中检测到一个或多个验证错误:” enter image description here

请帮我解决这个问题,把我需要的存档。

最佳答案

像这样尝试:

  1. public class Projects
    {
        public Projects()
        {
            ApplicationUser = new HashSet<ApplicationUser>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<ApplicationUser> ApplicationUser { get; set;     }
    }
    
  2. 应用程序用户



    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {
            Projects = new HashSet<Projects>();
        }
        public async Task GenerateUserIdentityAsync(UserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }        
        public virtual ICollection <Projects > Projects { get; set; }
    }

  1. 应用环境:


    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }
        public virtual DbSet<Projects> Projects { get; set; }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

现在当我运行这个 Mvc 应用程序并注册时,我得到的数据库表如下所示:

From MSSQL

和正确的架构:

enter image description here

要问的事情很多,在我看来重要的是确定你是否: - 你可以/应该混合应用程序上下文和你的模型上下文吗?

关于entity-framework - Asp.Net MVC 5 中的多对多关系与身份表和自定义表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39676239/

相关文章:

error-handling - 在父页面上显示有错误的 mvc 局部 View

asp.net-mvc-3 - 使用Automapper/EF代码优先进行数据库更新

c# - 如何让用户在 C# EF4.1 Code First 中动态指定数据库提供程序和连接详细信息?

.net - 使用复合键在模型中创建关系会引发 "Property is part of key and can' t be modded”异常

c# - Entity Framework - 在数据库中保存枚举的 ICollection

c# - 使用扩展方法 (EF5) 恢复 DbContext.Detach() 方法

c# - 如何在 MySql 数据库中存储 List<string>

c# - 如何删除 Entity Framework 代码优先数据库中的相关对象?

angularjs - 如何在 mvc5 中使用 angular-google-maps 绘制多边形

asp.net - 在 ASP.NET MVC5 中执行长时间运行任务的最佳方法