多对多关联的编辑操作
我正在为网站上的新闻制作标签。首先使用实体框架代码。 PostTag关联表(PostId + TagId)是自动生成的。 这是我的模型:
public class Post
{
public int Id { get; set; }
//...
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
//...
public virtual ICollection<Post> Posts { get; set; }
}
问题在于为我的管理面板实现帖子编辑器操作。创建和删除操作工作正常。这是我尝试过的,它正确更新所有帖子字段,但忽略标签。
[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] TagId)
{
if (ModelState.IsValid)
{
post.Tags = new List<Tag> { };
if (TagId != null)
foreach (int f in TagId)
post.Tags.Add(db.Tags.Where(x => x.Id == f).First());
db.Entry(post).State = EntityState.Modified; // Doesnt update tags
db.SaveChanges();
return RedirectToAction("Index");
}
//...
解决方案
[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] TagId)
{
if (ModelState.IsValid)
{
Post postAttached = db.Posts.Where(x => x.Id == post.Id).First();
post.Tags = postAttached.Tags;
post.Tags.Clear();
if (TagId != null)
foreach (int f in TagId)
post.Tags.Add(db.Tags.Where(x => x.Id == f).First());
db.Entry(postAttached).CurrentValues.SetValues(post);
db.SaveChanges();
return RedirectToAction("Index");
}
感谢 gdoron 指明方向。
I'm making tags for news on web site. Using Entity Framework Code First. PostTag association table (PostId + TagId) is automatically generated.
Here are my models:
public class Post
{
public int Id { get; set; }
//...
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
//...
public virtual ICollection<Post> Posts { get; set; }
}
The problem is in implementing Post Editor Action for my administration panel. Create and Delete actions work fine. Here is what I've tried, it updates all the Post fields properly, but ignores Tags.
[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] TagId)
{
if (ModelState.IsValid)
{
post.Tags = new List<Tag> { };
if (TagId != null)
foreach (int f in TagId)
post.Tags.Add(db.Tags.Where(x => x.Id == f).First());
db.Entry(post).State = EntityState.Modified; // Doesnt update tags
db.SaveChanges();
return RedirectToAction("Index");
}
//...
Solution
[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] TagId)
{
if (ModelState.IsValid)
{
Post postAttached = db.Posts.Where(x => x.Id == post.Id).First();
post.Tags = postAttached.Tags;
post.Tags.Clear();
if (TagId != null)
foreach (int f in TagId)
post.Tags.Add(db.Tags.Where(x => x.Id == f).First());
db.Entry(postAttached).CurrentValues.SetValues(post);
db.SaveChanges();
return RedirectToAction("Index");
}
Thankx to gdoron for pointing the direction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的建议:
我没有测试过,你能帮我们确认一下吗?
My sugestion:
I do not tested, could you confirm it for us?