【问题标题】:How to add a many-to-many relationship to Identity default table AspNetUsers with code first?如何首先使用代码向 Identity 默认表 AspNetUsers 添加多对多关系?
【发布时间】:2015-10-27 17:37:51
【问题描述】:

我是 Identity 框架和 Code First 方法的新手。现在我在 VS 2015 上创建新的 MVC5 项目时使用默认项目。

运行项目时生成的默认表很好,但我希望它与其他表一起生成一个名为 tbSkills (Id, SkillName) 的新表,并且它必须与 AspNetUsers 具有多对多关系。

那么我必须在哪里写什么来完成这个?

ps:我还按照教程将 Id 类型从 string 更改为 int,效果很好。

这是我最后尝试的,在 ApplicationUser 类中的 IdentityModels.cs 文件中:

public class ApplicationUser : IdentityUser<int, MyUserLogin, MyUserRole, MyUserClaim>, IUser<int>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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;
    }

    // // This following is my added code 
    public ApplicationUser()
    {
        Skills = new HashSet<tbSkill>();
    }

    public virtual ICollection<tbSkill> Skills { get; set; }
}

public class tbSkill
{
    public tbSkill()
    {
        Users = new HashSet<ApplicationUser>();
    }

    public int Id;
    public string SkillName;

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

以这个错误结束:

我已经研究和阅读了一堆文章,但没有成功。

【问题讨论】:

    标签: ef-code-first asp.net-identity-2


    【解决方案1】:

    尝试添加技能ID

    public class ApplicationUser : IdentityUser<int, MyUserLogin, MyUserRole, MyUserClaim>, IUser<int>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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;
        }
    
        // // This following is my added code 
        public ApplicationUser()
        {
            Skills = new HashSet<tbSkill>();
        }
        public int SkillId {get;set;}
        public virtual ICollection<tbSkill> Skills { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      相关资源
      最近更新 更多