Add IdentityUser as property of other model

Viewed 1711

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 hellogoodnight@gmail.com 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?

1 Answers
Related