2

我一直在关注 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但更新模型似乎不属于那里的行为。

还有其他方法吗?

谢谢你。

4

1 回答 1

2

从错误中,我假设您的两个IPostRepository实现对象使用不同的实体框架对象上下文;您可以通过在整个请求中使用相同的对象上下文来解决此问题。

一些 DI 容器支持每个请求的对象生命周期,否则您可以延迟加载并将对象上下文存储在HttpContext.Items其中并在请求结束时将其处置,如本问题所述。

于 2012-01-30T20:44:09.790 回答