Search code examples
c#asp.netasp.net-mvc-5scaffolding

ASP.NET MVC 5 saving current ApplicationUser


I'm trying to make it possible for a logged in application user the send a request, that request should be saved in the database with a RequestID, Content, UserID.

Everything works fine when I scaffold it (database is created with user_id) but it doesn't save the user id (NULL). Should the id get saved automatically because of the public ApplicationUser variable or am I missing code to make it work?

Request:

//Request.cs

public int RequestID { get; set; }
public string Content { get; set; }
public ApplicationUser user { get; set; }

Create view & Database:

enter image description here


Solution

  • There is no such automatic mechanism, it can be any instance of ApplicationUser.

    Thus, before saving the Request instance to the database, set the user explicitly:

    request.user = UserManager.FindById(User.Identity.GetUserId());