3

I have an ASP.NET Core MVC application. I am using ASP.NET Identity for user management. Each user can log in to the application and have their own page where they can keep and modify their let's say favorite movies.

My problem is how to identify movies by the users?

My first guess was to add list of movies to the user class, but I feel like it is wrong since the User class should only contain data concerning identity.

class User : IdentityUser
{
    public List<Movie> MovieList { get;set; }
}

My second thought was to add UserId to the Movie class but this feels like mixing models again... And that would make retrieving the data in controllers somewhat ugly...

class Movie
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string UserId { get; set; }
}

I am just beginning my adventure with ASP.NET so I am a bit confused here. What is the official correct way to add user data (not regarding identity) to user?

wizir
  • 71
  • 6

3 Answers3

6

You could create a separate model which will hold UserId and MovieId. For example:

class UserFavouriteMovies
{
  public int Id { get; set; }
  public int MovieId {get; set; }
  public int UserId { get; set; }
}

Then you could display all movies from this table based on a logged in user.

Seb
  • 116
  • 9
2

If you want to only have data concerning identity on Users and not have User IDs on movies, you could create an associative table called UserMovies that contains a user ID and a list of movies, like so :

class UserMovies 
{
    public int Id;
    public string UserID; // or whatever datatype you're using to store user IDs.
    public List<Movie> Movies;
}
Jud
  • 1,324
  • 3
  • 24
  • 47
1

You could create another table to link them.

class User : IdentityUser
{
    public virtual ICollection<UserMovie> UserMovieList { get; set; }
}

class UserMovie 
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int MovieId { get; set; }

    [ForeignKey("UserId")]
    public virtual User User { get; set; }

    [ForeignKey("MovieId")]
    public virtual Movie Movie { get; set; }
}

class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string UserId { get; set; }
}

var user = db.User.Include("UserMovieList").ToList();
for (int i = 0; i < user.UserMovieList.Count; i++)
{
    var movie = user.UserMovieList[i].Movie;
    // ...
}

// To get all movies of specific user
var specificUser = db.User.Find("user id").ToList().SelectMany(a => a.Movie);

Other example: How to create a many-to-many mapping in Entity Framework?

Marcelo Vismari
  • 1,147
  • 7
  • 15