【发布时间】:2015-07-09 12:32:38
【问题描述】:
我遇到了一个非常奇怪的问题,我无法解释。我可以创建一个新实体并将其链接到他的外键,但我无法更新。这是我的代码
我的 Post.cs 实体:
public class Post(){
public int Id {get;set;}
public string Title {get;set;}
...
public int PostCategoryId {get;set;}
public virtual Category Category {get;set;}
}
我的 Category.cs 实体:
public class Category(){
public int Id {get;set;}
public string Title {get;set;}
...
public virtual IList<Post> Posts {get;set;}
}
控制器中的更新方法:
[HttpPost]
public ActionResult EditPost(Post post) {
....
_repository.UpdatePost(post);
以及存储库中的 UpdatePost 方法:
public void UpdatePost(Post post){
var category = _db.Category.SingleOrDefault(x => x.Id == post.PostCategoryId);
post.Category = category;
// I clearly see that the post have the category in the object
_db.Entry(post).State = EntityState.Modified;
_db.SaveChanges();
我的对象的每个属性都会更新,除非类别。
有人有解决办法吗?
非常感谢,因为这个问题我睡不着:)
【问题讨论】:
标签: c# asp.net entity-framework asp.net-mvc-5 ef-code-first