Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access UserProfile from a controller MVC 4

New to all this: I have a model for Character that has a UserProfile property, so that a character can be assiciated with a UserProfile entry. This would make UserProfile a foreign key for a Character.

Character Model:

public class Character
{
    public int ID { get; set; }
    public virtual UserProfile user { get; set; }
    public string name { get; set; }
...
}

(I made the UserProfile property virtual because of another post, not sure if this should stay)

When creating a new character I want to set the user property of that character to the object of the current web-user making the request. For example here is the process a user would take to make a character: Login/Create User account with site Click 'Create Character'

[HttpPost]
public ActionResult Create(Character character)
{
    if (ModelState.IsValid)
    {
        character.user = ???
        db.Characters.Add(character);
        db.SaveChanges();
        ...
}

Problem is I do not know how to access the UserProfile table from my controller. Typically to access a table I create an object of my dbContext but the UserProfile table is using the default MVC 4 context while all the other objects of my app are using a different dbContext.

I'm guessing there are a few solutions for me, none of which I can figure out how to do:

  1. Should I set up my application so all tables use 1 dbContext? If so, how?
  2. Is there some way to create an object of the default dbContext that UserProfile is already using?

Sorry in advance if any of my terminology is off or if I left out vital information. I'll provide more as needed. Thanks

like image 574
Chris Stevens Avatar asked Apr 19 '13 21:04

Chris Stevens


1 Answers

When you logged in your user information like UserId or UserName will be stored in

WebSecurity.CurrentUserId

WebSecurity.CurrentUserName

[HttpPost]
public ActionResult Create(Character character)
{
    if (ModelState.IsValid)
    {
        character.user = db.UserProfiles.Find(u => u.UserID = WebSecurity.CurrentUserId); 

        db.Characters.Add(character);
        db.SaveChanges();
    ...
}
like image 142
Moshiur Rahman Avatar answered Oct 01 '22 11:10

Moshiur Rahman