Entity Framework 5、MVC 4、および CodeProject の CheckBoxList 1.4.4.3-beta2 を使用して、多対多の関係で UserProfile オブジェクトの Roles 関係を単純にクリアしようとしています。
UserProfileController (縮小 - スカラー プロパティと選択したロールを保存しません):
[Authorize]
public ActionResult Edit(int identifier)
{
var unitOfWork = new UnitOfWork();
using(var userProfileRepository = new UserProfileRepository(unitOfWork))
{
UserProfile user = userProfileRepository.AllIncluding(u => u.Roles).Single(u => u.UserId == identifier);
UserProfileViewModel viewModel;
using (var roleRepository = new RoleRepository(unitOfWork))
{
viewModel = new UserProfileViewModel()
{
AllRoles = roleRepository.All.ToList(),
UserProfile = user
};
}
return View(viewModel);
}
}
[HttpPost]
[Authorize]
public ActionResult Edit(UserProfileViewModel viewModel, string[] roleIds)
{
var unitOfWork = new UnitOfWork();
using (var userProfileRepository = new UserProfileRepository(unitOfWork))
{
if (ModelState.IsValid)
{
var user = userProfileRepository.AllIncluding(u => u.Roles).Single(u => u.UserId == viewModel.UserProfile.UserId);
user.Roles.Clear();
userProfileRepository.InsertOrUpdate(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
return View(viewModel);
}
}
UserProfileRepository (および RoleRepository) は、標準のスキャフォールディング リポジトリです。
public void InsertOrUpdate(UserProfile userprofile)
{
if (userprofile.UserId == default(int)) {
// New entity
context.UserProfiles.Add(userprofile);
} else {
//// Existing entity
context.Entry(userprofile).State = EntityState.Modified;
}
}
ユーザープロフィール:
public ICollection<Role> Roles { get; set; }
役割:
public ICollection<UserProfile> UserProfiles { get; set; }
例外は発生しませんが、データベースへの更新も実行されません。同じ db テーブルを使用している認証プロバイダー (SimpleMembershipProvider) が原因でしょうか? カスタム メンバーシップ プロバイダーを実装する必要がありますか? 私のアプリケーションには他にもいくつかの多対多の関係があり、すべてこれと同じ方法で構成されており、それらはすべて魅力的に機能します。