Differentiate list of items shown in View using "Individual User Account" Asp.Net MVC 5

0

I do not have much practice in programming and I'm creating a system for registering items like movies, books, games, etc. for a college job. The problem is that I need to use a user manager system so that in the view index of each item type show only what the user registers, for example:

João has registered in his list of films "The Departed" and "Fight Club"; José has registered on his list of films "Harry Potter" and "The Lord of the Rings".

When John logs in, he should only submit the films registered by him, in the same way that when José logs in, he should only submit the films registered by him.

I created the project using "Individual User Account".

Would anyone help me?

Thank you!

    
asked by anonymous 25.02.2016 / 20:12

1 answer

2

Projects with "Individual User Accounts" come with ASP.NET Identity installed by default. To do what you want, your entities should be modeled containing the following:

public class Filme
{
    [Key]
    public int FilmeId { get; set; } // Essa é a chave primária.
    public String UsuarioId { get; set; } // Essa é a chave estrangeira, obrigatória.

    // Coloque o resto dos campos aqui

    public virtual ApplicationUser Usuario { get; set; } // Esta linha é a mais importante, 
                                                         // determinando que um filme pertence
                                                         // a um usuário.
}

When saving a record, register the current user as the "owner" of the record.

filme.UsuarioId = User.Identity.GetUserId();

When reading logs, select the logged in user:

var usuarioId = User.Identity.GetUserId();
var filmes = db.Filmes.Where(f => f.UsuarioId == usuarioId).ToList();

An elegant way to bring objects bound to the user is to change the class ApplicationUser to the following:

public class ApplicationUser: IdentityUser
{
    // Coloque aqui campos que você quer que o usuário tenha.

    public virtual ICollection<Filme> Filmes { get; set; }
}

Controller do so:

var usuarioId = User.Identity.GetUserId();
var usuario = db.Usuarios.Include(u => u.Filmes).FirstOrDefault(u => u.UsuarioId == usuarioId);

var filmes = usuario.Filmes.ToList();
    
25.02.2016 / 20:43