It should be something simple, not sure why I couldn't find the solution on the web. Maybe it's specific to EF6 or ASP Identity or, maybe I'm entering wrong search key words.
To simplify things, let's say I have two model classes Teacher and Kid; One kid can be assigned only to one teacher, but one teacher can have many kids. It's multi-user environment, so each Kid and each Teacher belong to particular user. As I'm using code first, my database is constructed from these model classes:
public class Kid
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public virtual Teacher { get; set; }
[Required]
public virtual ApplicationUser User { get; set; }
}
public class Teacher
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Kid> Kids { get; set; }
[Required]
public virtual ApplicationUser User { get; set; }
}
I have a view for adding new kid with: Textbox for Kid's name; Dropdown with list of Teachers
So, I'm creating a data transfer object, specifically for that view:
public class AddNewKidViewDTO
{
public string Name {get; set;}
public IEnumerable<SelectListItem> Teachers { get; set; }
public int SelectedTeacherId { get; set; }
}
Form gets submitted and I get my populated AddNewKidViewDTO model.
Now, I need to insert a new Kid into the database. So, I map AddNewKidViewDTO properties to my Kid model properties one by one:
public void InsertNewKid {AddNewKidViewDTO addNewKidViewDTO}
{
Kid kid = new Kid();
kid.Name = AddNewKidViewDTO.Name;
// here comes the question. How do I set Kid.Teacher and Kid.User?
}
UPDATE 1
I'm NOT asking how to get selected teacher id. I need to know how to assign navigation property to model object (using that id).
UPDATE 2:
If I get current user object like this:
ApplicationUser user = usermanager.FindById(User.Identity.GetUserId<int>());
And then attach it to Kid:
Kid.User = user;
On Kid insert, it throws exception:
The member with identity 'mynamespace.DAL.Kid_User' does not exist in the metadata collection.
Any help appreciated.