Frip
Frip

Reputation: 884

How to create relationships (one-to-one, many-to-many) for ASP.Net Identity Users model

I need create 2 relationships for Identity.User

  1. One-to-One (i know, that is so bad, but i need this)

For example, to set additional user characteristics.

  1. Many-to-Many

For example, for model of Books. User can have many books and a book can be with many users. Like in the library.

How I can do this. Thanks.

Upvotes: 0

Views: 118

Answers (2)

Jonathan Alfaro
Jonathan Alfaro

Reputation: 4376

First of all. Many to Many Foreign Keys are not supported in SQL Server. The only way to achieve this (at least the only way I know) is to create a "mapping" table.

So you need three tables User, Books and UserBooks.

I will not dive into the details on how to do it but I will point you in the right direction.

Here is a Many To Many Tutorial on how to do this.

Here is Another Tutorial

The second one shows the table schema. This is pretty common.

I hope this helps you achieve your goal.

Upvotes: 1

li223
li223

Reputation: 369

You can inherit from IdentityUser and pass your custom object that inherits from it in IdentityDbContext<>. Then your custom object can have additional members that you need including collection of books or singular properties.

Then you define the relationship when overriding OnModelCreating as specified here

As a rough example:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<CustomUser>()
        .HasOne(p => p.Name)
        .WithMany(b => b.Books);
}

Hope this helps.

Upvotes: 0

Related Questions