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:
Sorry in advance if any of my terminology is off or if I left out vital information. I'll provide more as needed. Thanks
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();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With