Add relationships to the ApplicationUser class in ASP.NET Identity (Database First)

前端 未结 2 547
长情又很酷
长情又很酷 2021-01-13 08:19

I\'m using ASP.NET Identity (Database First) in my ASP.NET MVC application. I followed the instructions here, to set up the ASP.NET Identity with database first approach.

2条回答
  •  旧时难觅i
    2021-01-13 08:46

    Concern:


    I know exactly what your burden is here. Yes, Microsoft, an esoteric cult, did very poor job in providing the information to this matter that is creating a relationship with the Identity (Entity Framework).

    Contribution:
    Ruard van Elburg post on Aug 24 at 16:31 gives good insight on this matter; however, there was one key component that I noticed was missing in his code which was DbSet that needed to be placed in the DBContext of IdentityModels.

    Tech Stack:
    I provide my tech stack so that if this does not work with older versions of software, you will know what I used to get this issue resolved.

    • Visual Studio 2017 MVC 5. FYI, MVC 5 is built in into most recent VS.
    • SQL Server 17
    • MS SQL Management Studio 17


    Solution:


    Disclaimer!!! I understand that the concern is for database first; however, this solution is only for code first approach. But hey, it works!

    Here I provide a walk through on how to do this. Please make sure you have all the dependencies in top margin of your code.

    Step 1: Add public virtual DbSet ModelNameOfInterest { get; set; } to public class ApplicationDbContext : IdentityDbContext{} as seen in code below.

    using System.Data.Entity;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
        using System.ComponentModel.DataAnnotations.Schema;
    
    namespace AwesomeCode.Models
    {
        // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
        public class ApplicationUser : IdentityUser
        {
    
            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 class ApplicationDbContext : IdentityDbContext
        {
            public ApplicationDbContext()
                : base("DefaultConnection", throwIfV1Schema: false)
            {
            }
            //A virtul DbSet in order to interact with the autogenerated code the identity framewrok produces.
            public virtual DbSet ModelNameOfInterest { get; set; }
    
            public static ApplicationDbContext Create()
            {
    
                return new ApplicationDbContext();
            }
    
    
    
        }
    }
    

    Step 2: Add public virtual ApplicationUser ApplicationUser { get; set; } to your model that you want to create a relationship with as seen code below.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace AwesomeCode.Models
    {
        public class WorkExp
        {
            [Key]
            public int Id { get; set; }
            public string JobTitle { get; set; }
    
            //Create foreign key with reference to ApplicationUser_Id that was auto-generated by entity framework.
            public virtual ApplicationUser ApplicationUser { get; set; }
        }
    }
    

    Step 3: Given that you set up your connection string for your database, you need to produce a migration. Path to Package Manager Console: Tools->NuGet Packer Manager->Package Manager Console

    • Enable a migration if migration folder is absent in root: After PM>, type Enable-Migrations you should see a migration folder with two files.
    • Once migration is enabled: After PM>, type Update-Database You should see tables in your database now.
    • To add another migration: After PM>, type Add-Migration After Name:, type InitialCreate or Your model of interest You should see tables in your database now. You should see tables in your database now.


    Step 4: Double check that the model of interest's foreign key is properly referenced to the AspNetUser table. In MS Management Studio, you can create a relational diagram to show the references. You can find how to do that on google.

    Step 5: As always stay cool, calm, and collected.

提交回复
热议问题