User data in MVC

I’m trying to figure which way is the best way of storing data acessible only for the user that is logged in.

For example: the classic category tutorial, but being acessible only to the user that created it.

My ideas at the moment are simple: creating an User model and making the other models(Category, for example) it’s child.

Is there any clever way of doing this using ASP.NET MVC? When using the Identity we already have Users credentials for authorization, I just want to make data available only for the user that created it.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

When using the Identity we already have Users credentials for authorization, I just want to make data available only for the user that created it.

If you configure and integrate Identity in your application, you can try to establish a one-to-many relationship between the Category and ApplicationUser entities where many categories are associated with one ApplicationUser.

public class ApplicationUser : IdentityUser
{
    //...
    //code here
    //...
}

public class Category
{
    public string CategoryId { get; set; }

    //...
    //other properties of category
    //...

    public string UserId { get; set; }

    public ApplicationUser User { get; set; }
}

Then you can query data that specific user created based on UserId, like below.
//get user id of current logged-in user 
//then query data based on currentUserId

var category_list = _dbcontext.Categories.Where(c => c.UserId == currentUserId).ToList();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x