I'm a newbie with MVC + EF Code First and have some doubts about many to many relationship.
I created 2 tables that has many to many relationship (userprofile and courses). Sounds simple but it got pretty complex for me:
I want to see the "create" view of the "userprofile" with checkboxed for each of the "courses"existent options and being able to save it to corresponding databases.
I've been reading and looking for examples but I didn't get to solved this (or to find any related information about this particular need (I found similar things that didn't apply)
I already saw this article but it's not about the create and not using EF (http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application)
public class UserProfile
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Courses> usercourses { get; set; }
}
public class Courses
{
public int CourseID { get; set; }
public string CourseDescripcion { get; set; }
public virtual ICollection<UserProfile> UserProfiles { get; set; }
}
public class UserProfileDBContext : DbContext
{
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Courses> usrCourses{ get; set; }
}
The Create Controler:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userprofile);
}
Regarding the view, I would like to have just the '@foreach' loop for generating the dropboxes.