1

I really could use some assistance with an idea I'm working on.

I need a many to many relationship between IdentityModel and BookModel. Something like this. DB Diagram I come up with

Now in my code I have this in the IdentityModel.

public class ApplicationUser : IdentityUser
{

    public virtual ICollection<Book> Books { get; set; }

    ...
}


public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    ...
    public System.Data.Entity.DbSet<talkbooks.Models.Book> Books { get; set; }
}

And this in my Book Model

public class Book
{

    public int Id { get; set; }
    public string Name { get; set; }
    public string Isbn { get; set; }
    public virtual ICollection<ApplicationUser> Users { get; set; }

}

Now I want users to be able to select the books they own from the database (To keep it simple there is only one book in there right now and I want to use a dropdown list for selecting it) then have this stored in the database.

I thought about editing the already scaffolded ManageController to include a method that takes care of adding the books to their account.

Now when I create the database (code-first entity) it creates the Database as follows:

ERD

I left out DiscussionModel and MessageModel for the moment. Now I really need some help with the code needed to make this work inside the controller. I really have tried so much, and I keep failing, I know this is due to the fact I'm a beginner and lacking experience. So I want to learn from what you can teach me. All help is greatly appreciated!

Dennis VW
  • 2,977
  • 1
  • 15
  • 36
  • @Connell.O'Donnell I agree in part it is a duplication of that question. But in addition I need help creating the controller to handle this many-many relationship, and I can't find that anywhere really. – Dennis VW Apr 07 '17 at 14:04

1 Answers1

0

Your ApplicationDbContext uses EntityFramework so this has nothing to do with Identity 2.0 in the first place but with EntityFramework itself.

To create Relationships in Entity Framework you have two options:

  1. Using Annotations
  2. Using Fluent API

See this post for examples on both options. I prefer the Fluent API approach but I think this is really a personal thing. In this case your example would look like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>()
                .HasMany<ApplicationUser>(b => b.Users) // book entity has many users
                .WithMany(u => u.Books); // User entity includes many book entities
}
PtrBld
  • 64
  • 1
  • 6