Reputation: 731
I have three tables in my entity model of my database:
I can add category more than one to a post. So tables are many to many.
I can add new a post with more then one category. There are no problem.
CreatePost
action:
[HttpPost]
public ActionResult CreatePost(Post post, int[] categories)
{
post.CreatedDate = DateTime.Now;
foreach (var category in categories)
{
post.Categories.Add(db.Categories.Find(category));
}
db.Posts.Add(post);
db.SaveChanges();
// Get categories from ListBox
ViewData["Categories"] = new MultiSelectList(db.Categories.Select(c => new CategoryViewModel()
{
CategoryId = c.CategoryId,
CategoryName = c.Name
}), "CategoryId", "CategoryName");
return View(post);
}
But I can't update categories from post. I can't get error but it is not working.
EditPost
:
[HttpPost, ActionName("EditPost"), ValidateInput(false)]
public ActionResult EditPost(Post post, int[] categories)
{
ViewData["Categories"] = new MultiSelectList(db.Categories.Select(c => new CategoryViewModel()
{
CategoryId = c.CategoryId,
CategoryName = c.Name
}), "CategoryId", "CategoryName");
post.CreatedDate = DateTime.Now;
// Clear all categories.
post.Categories.Clear();
foreach (var category in categories)
{
// Add new categories.
post.Categories.Add(db.Categories.Find(category));
}
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Posts");
}
Categories are not updated when I edit a posting. I don't get any error. How can I do that? Help please..
Upvotes: 1
Views: 185
Reputation: 109089
The reason is that post.Categories
must be loaded before EF can track changes to it.
db.Entry(post).State = EntityState.Modified; // Also attaches post to the context
db.Entry(post).Collection(p => p.Categories).Load();
// Clear all categories.
post.Categories.Clear();
// and so on
By the way, are you sure of post.CreatedDate = DateTime.Now;
while the post is updated and not created?
Upvotes: 1
Reputation: 65391
The probable reason that nothing is saved is that SaveChanges does not find any changes to save. Therefore, it does nothing, and there is no error Message.
Try attaching the post to the context before adding the categories. Or setting the state on the categories:
foreach (var cat in post.Categories)
this.Entry(cat).State = EntityState.Modified;
Upvotes: 0