I have the following controller action to create a user.
public ActionResult Create([Bind(Include = "Name, Email, Role, Password")] User user)
{
if (ModelState.IsValid)
{
// Create password hash
user.Salt = Security.RandomString(16);
user.Password = Security.Encrypt(user.Password, user.Salt);
// Add Qualifications
var qualification = db.Qualifications.Find(5);
user.Qualifications.Add(qualification);
// Apply changes
db.Users.Add(user);
db.SaveChanges();
}
return RedirectToAction("Index");
}
It all works fine, besides the part of adding the Qualification for the user (I want to add multiple qualifications, once it works). The user model has this:
public virtual ICollection<Qualification> Qualifications { get; set; }
to store the qualifications (Its a many to many relationship, for which Entitiy Framework has already created a table).
I always get an error: "Object reference not set to an instance of an object.", at line: user.Qualifications.Add(qualification);
I dont understand why, after all, i did add Salt and Password properties the same way just before (and that works fine). Also I did add multiple qualifications to a user object in my seed method exactly the same way, where it also works fine.
Whats the problem here and how can i fix it?