User Profile Access from MVC 4

New to all of this: I have a model for Character that has a UserProfile property, so the character can be evaluated using the UserProfile entry. This would make UserProfile a foreign key for the 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 due to another message, not sure if this should remain)

When creating a new symbol, I want to set the user property of this symbol to the object of the current web user making the request. For example, here is a process that a user must take to create a character: Login / Create a user account with a site Click "Create Symbol"

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

, , UserProfile . dbContext, UserProfile MVC 4 dbContext.

, , , :

  • , 1 dbContext? , ?
  • dbContext, UserProfile?

, - . .

+5
2

, , . , :

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

        db.Characters.Add(character);
        db.SaveChanges();
    ...
}
+3

, UserId UserName,

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();
    ...
}
+7

All Articles