私はMVC+EF Code Firstの初心者であり、多対多の関係について疑問を持っています。
多対多の関係(ユーザープロファイルとコース)を持つ2つのテーブルを作成しました。単純に聞こえますが、私にとってはかなり複雑になりました。
「コース」の既存のオプションごとにチェックマークが付いた「ユーザープロファイル」の「作成」ビューを表示し、対応するデータベースに保存できるようにしたい。
私は例を読んで探していましたが、これを解決することができませんでした(またはこの特定のニーズに関する関連情報を見つけることができませんでした(私は当てはまらない同様のものを見つけました)
私はすでにこの記事を見ましたが、それは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; }
}
作成コントローラー:
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);
}
ビューに関しては、ドロップボックスを生成するための「@foreach」ループだけが必要です。