0

I am learning ASP.NET MVC 5 and EF. I want each registered user to be able to create a simple list of their belonging items.

So I have an Item class in Model folder:

class Item 
{
   public int Id {get; set;}
   public string Name {get; set;}
}

How can I update my database using code first approach so that user can have a foreign key to Items table so that I can query all items that belong to the current user?

Select * 
From Items 
Where userID = currentUserID
1
  • To be honest. use ASP.NET Identity 2.2. it handles everything you need about user Authorization or Authentication. You can even extend it to use your own entities for user profile. It'll use EF(code-first) as well tho it has its own dbcontext. Commented Aug 26, 2017 at 9:20

1 Answer 1

1

You will need to have item as a separate entity(Model) then create a relationship with the user. When you use this approach EF will create respective tables with their relationships(one to many i.e one user can have many entities).

Here is how its implemented in code.

Item Class

public class Item 
{
   public int Id {get; set;}
   public string Name {get; set;}

   //foreign key
   public int UserId {get; set;}

   //Navigation property 
   public virtual ApplicationUser User{get; set;}
}

Application user class

public class ApplicationUser : IdentityUser
{
    //Here you can add more properties if you wish to
    public string FirstName{ get; set; }
    public string LastName { get; set; }

    //User-Item relationship (user can have many Items)
    public virtual List<Item> Items { get; set; }
}

Then you will have to go to ApplicationDbContext and add DbSet of Item as below

public class ApplicationDbContext : IdentityDbContext<SchedulerUser>
{
    public virtual DbSet<Item> Items { get; set; }

    //some code are excluded for clarity
}

To get the list of all items that belong to the user you can query using linq like

var _db = new ApplicationDbContext();
var Items = _db.Users.Find(UserId).Items.ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.