Search code examples
c#asp.net-mvcentity-frameworkasp.net-identity

Add IdentityUser as property of other model


I´m playing around with ASP.NET Identity, using MVC5 and EntityFramework 6.1.3. My problem is that I cannot add an IdentityUser as a property to another model.

My application lets a user create a Project:

 public class Project
    {
        public int ProjectID { get; set; }
        public string ProjectName { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

In the action method for creating a new project, I'm trying to add the signed in user like this:

public ActionResult Create([Bind(Include = "ProjectID,ProjectName")] Project project)
        {
            if (ModelState.IsValid)
            {
                // I added the first two lines of code below. 
                var loggedInUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
                project.ApplicationUser = loggedInUser;
                db.Projects.Add(project);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(project);
        }

loggedInUser is set correct, it gets all the right properties. However, when I try to save the updated context, I get the following error:

"Validation failed for one or more entities. The validation errors are: User name [email protected] is already taken."

So, for some reason my code apparently tries to create a new user, instead of adding the existing one to the created Project. Why? Is this not the way to add an IdentityUser as a navigation property to a model?


Solution

  • I suppose you have two tables with an one to many relationship.

    Project entity can have only one user attached and user entity can have one or many projects.

    Thus, you need to attach the foreign key in your Project class in order to allow Entity framework to map relationships correctly and establish associations between relational model ( database ) and conceptual model.

     public class Project
     {
        public int ProjectID { get; set; }
        public string ProjectName { get; set; }
        public int ApplicationUserId{ get; set;}
        public virtual ApplicationUser ApplicationUser { get; set; }
     }