5

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

4

2 回答 2

7

当您登录时,您的用户信息(如 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();
    ...
}
于 2013-05-05T18:55:47.060 回答
3

我通常将当前用户 ID 保存在会话变量中,然后在需要时从数据库中检索该用户。所以代码可能看起来像:

[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();
    ...
}
于 2013-04-19T21:36:16.830 回答