简体   繁体   中英

How to add tables and relations to generated Asp.Net Core MVC Identity database?

I have a project where I have to make an ASP.NET Core MVC Web Application in which I should include user sign up, login, and an SQL database with basic CRUD operations and corresponding views. For login and signup I decided to use Asp.Net Core Identity following this tutorial: https://youtu.be/CzRM-hOe35o . Everything works and looks fine for signup and login but I can't figure out how to use my database with the database generated by Identity. My idea for a project database was to have a table for a User and Article (there are more tables but I'm going to keep it simple to explain my problem) with one to many relation. Now that I have a generated database for all things about Users(from Identity tutorial) how can I include this Article table in the databse and make a one to many relation between AspNetUsers and Article? Or can I use two databases in my project, one with Users and the other one with other project tables? But then how to make relations between tables from different databases, and is it even possible?

First of all, you should know that you can use two databases but never on this case.

To do what you want, follow those steps:

Step 1 - Create a class called "User" in project folder called "Data". Class will be like this:

public class User : IdentityUser
{
   
}

Step 2- Create another class called "Article" in the same folder called "Data".

 public class Article
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public virtual User User { get; set; }
}

Step 3 - Go to "User" class that you created in the step one and edit it to look like this

 public class User : IdentityUser
{
    public virtual ICollection<Article> Articles { get; set; }
}

Step 4 - In the same folder where you added those two classes you have another class called "ApplicationDbContext". Open it and register User and Article classes.

 public class ApplicationDbContext : IdentityDbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Article> Articles { get; set; }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

Step 5 - delete in your local database the existing db generated from your project before. After that "Add-migration" and "Update-database"

For more information about how Entity Framework Core works see the link: https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship#:~:text=The%20easiest%20way%20to%20configure,public%20class%20Author

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