3つのモデルがあるとしましょう:
[Table("UserProfile")]
public class UserProfile //this is a standard class from MVC4 Internet template
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public int UserProfileId { get; set; }
[ForeignKey("UserProfileId")]
public virtual UserProfile UserProfile { get; set; }
}
今、投稿を編集しようとしています
[HttpPost]
public ActionResult Edit(Post post)
{
post.UserProfileId = context.UserProfile.Where(p => p.UserName == User.Identity.Name).Select(p => p.UserId).FirstOrDefault();
//I have to populate post.Category manually
//post.Category = context.Category.Where(p => p.Id == post.CategoryId).Select(p => p).FirstOrDefault();
if (ModelState.IsValid)
{
context.Entry(post.Category).State = EntityState.Modified; //Exception
context.Entry(post.UserProfile).State = EntityState.Modified;
context.Entry(post).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
そして、ArgumentNullExceptionを取得しています。デバッグを簡単に調べると、CategoryId が適切な値に設定されていても、Categoryがnullであることがわかります。
コメントアウトされた、見栄えの悪いトリックがこの問題を解決しますが、まったく存在しないはずです。問題は、それを適切に解決する方法です。
Postを追加するための非常によく似たコードがあり、デバッグには同じシーンがあります。適切なCategoryId、Categoryがnullであるにもかかわらず、EF はそのPost <-> Category依存関係を自動的に解決します。追加のトリックを使用する必要はありません。編集方法では、EF に問題がありますが、何が間違っているのかわかりません。