我一直在关注 Darin 对我的控制器瘦身问题的回答,但我遇到了这个IEntityChangeTracker
例外的问题:
一个实体对象不能被多个 IEntityChangeTracker 实例引用。
这是我的模型活页夹:
public class PostModelBinder : IModelBinder
{
private readonly IPostRepository _repository;
public PostModelBinder(IPostRepository repository)
{
_repository = repository;
}
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var postIDValue = controllerContext.Controller.ValueProvider.GetValue("postID");
int postID;
if (postIDValue == null || !int.TryParse(postIDValue.AttemptedValue, out postID))
return null;
return _repository.FindPost(postID, filterByPublished: true);
}
}
在此之后,我的自定义操作过滤器只需对帖子进行一些验证,并在帖子无效时重定向。到目前为止,一切都很好。当我尝试更新帖子读取计数时,错误发生在我的控制器中:
public class PostsController : Controller
{
private IPostRepository postRepository;
// snip...
[AutoMap(typeof(Post), typeof(PostViewModel)), HttpGet]
[PostActionFilter]
public ActionResult ShowPost(Post model)
{
postRepository.PostVisited(model);
return View(model);
}
}
我理解IEntityChangeTracker
的抱怨,因为我实际上最终得到了 2 个引用同一个对象的存储库,这似乎是等待发生的糟糕魔力。我知道我可以将PostVisited()
电话推入,PostModelBinder
但更新模型似乎不属于那里的行为。
还有其他方法吗?
谢谢你。