Ninject MVC 2,EF 4,AutoMapper - ObjectContext已被处理

时间:2012-05-10 00:54:30

标签: c#-4.0 asp.net-mvc-2 entity-framework-4 automapper ninject.web.mvc

完全修订:

好的,我正在使用Ninject和MVC 2扩展作为我的DI容器,而AutoMapper作为我的实体< - >查看模型映射器。我的视图模型中出现'ObjectContext is dispos'错误 - >实体映射。我的代码如下。

Ninject绑定:

public class DIModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<HGEntities>().ToSelf().InRequestScope();
        this.Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
        this.Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
        this.Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
        this.Bind<ErrorController>().ToSelf().InRequestScope();
        this.Bind<HGController>().ToSelf().InRequestScope();
    }
}

我的存储库:

public class HGGameRepository : IGameRepository, IDisposable
{
    private HGEntities _context;

    public HGGameRepository(HGEntities context)
    {
        this._context = context;
    }

    // methods

    public void SaveGame(Game game)
    {
        if (game.GameID > 0)
        {
            _context.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);
        }
        else
        {
            _context.Games.AddObject(game);
        }

        _context.SaveChanges();
    }

    public void Dispose()
    {
        if (this._context != null)
        {
            this._context.Dispose();
        }
    }
}

我的控制器的构造函数,其中包含我的AutoMapper地图定义:

    public AdminController(IArticleRepository articleRepository, IGameRepository gameRepository, INewsRepository newsRepository)
    {
        _articleRepository = articleRepository;
        _gameRepository    = gameRepository;
        _newsRepository    = newsRepository;

        Mapper.CreateMap<Game, AdminGameViewModel>()
            .BeforeMap((s, d) =>
            {
                int platCount = s.Platforms.Count;
                var plats = s.Platforms.ToArray();
                d.PlatformIDs = new int[platCount];

                for (int i = 0; i < platCount; ++i)
                {
                    d.PlatformIDs[i] = plats[i].PlatformID;
                }
            })
            .ForMember(dest => dest.Pros, opt => opt.MapFrom(src => src.Pros.Split(new char[] {'|'})))
            .ForMember(dest => dest.Cons, opt => opt.MapFrom(src => src.Cons.Split(new char[] {'|'})))
            .ForMember(dest => dest.PlatformIDs, opt => opt.Ignore());

        Mapper.CreateMap<AdminGameViewModel, Game>()
            .BeforeMap((s, d) =>
            {
                if (d.Platforms != null && d.Platforms.Count > 0)
                {
                    var oldPlats = d.Platforms.ToArray();

                    foreach (var oldPlat in oldPlats)
                    {
                        d.Platforms.Remove(oldPlat);
                    }
                }

                foreach (var platId in s.PlatformIDs)
                {
                    var plat = _gameRepository.GetPlatform(platId);
                    d.Platforms.Add(plat);
                }
            })
            .ForMember(dest => dest.Platforms, opt => opt.Ignore())
            .ForMember(dest => dest.BoxArtPath, opt => opt.Ignore())
            .ForMember(dest => dest.IndexImagePath, opt => opt.Ignore())
            .ForMember(dest => dest.Cons, opt => opt.MapFrom(src => string.Join("|", src.Cons)))
            .ForMember(dest => dest.Pros, opt => opt.MapFrom(src => string.Join("|", src.Pros)))
            .ForMember(dest => dest.LastModified, opt => opt.UseValue(DateTime.Now));
    }

这是第二个重要的映射。

接下来是我的编辑方法:

    [HttpPost]
    public ActionResult EditGame([Bind(Prefix="GameData")]AdminGameViewModel formData)
    {
        Game game = _gameRepository.GetGame(formData.GameID);

        if (ModelState.IsValid)
        {
            game = AutoMapper.Mapper.Map<AdminGameViewModel, Game>(formData, game);

    // it dies here, so the rest of the method is immaterial
    }

最后,堆栈跟踪:

[ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.]
System.Data.Objects.ObjectContext.EnsureConnection() +87
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +90
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +96
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +182
System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1(IEnumerable`1 sequence) +74
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +95
System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +163
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source, Expression`1 predicate) +300
HandiGamer.Domain.Concrete.HGGameRepository.GetPlatform(Int32 id) in C:\Users\Kevin\documents\visual studio 2010\Projects\HandiGamer\HandiGamer.Domain\Concrete\HGGameRepository.cs:68
HandiGamer.WebUI.Controllers.AdminController.<.ctor>b__a(AdminGameViewModel s, Game d) in C:\Users\Kevin\documents\visual studio 2010\Projects\HandiGamer\HandiGamer\Controllers\AdminController.cs:56
AutoMapper.<>c__DisplayClass1b.<BeforeMap>b__1a(Object src, Object dest) +139
AutoMapper.TypeMap.<get_BeforeMap>b__0(Object src, Object dest) +118
AutoMapper.Mappers.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper) +196
AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper) +256
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +459

[AutoMapperMappingException: 

Mapping types:
AdminGameViewModel -> Game
HandiGamer.WebUI.ViewModels.AdminGameViewModel -> HandiGamer.Domain.Entities.Game

Destination path:
Game

Source value:
HandiGamer.WebUI.ViewModels.AdminGameViewModel]
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) +537
AutoMapper.MappingEngine.Map(Object source, Object destination, Type sourceType, Type destinationType, Action`1 opts) +179
AutoMapper.MappingEngine.Map(TSource source, TDestination destination, Action`1 opts) +190
AutoMapper.MappingEngine.Map(TSource source, TDestination destination) +146
AutoMapper.Mapper.Map(TSource source, TDestination destination) +105
HandiGamer.WebUI.Controllers.AdminController.EditGame(AdminGameViewModel formData) in C:\Users\Kevin\documents\visual studio 2010\Projects\HandiGamer\HandiGamer\Controllers\AdminController.cs:323
lambda_method(Closure , ControllerBase , Object[] ) +162
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +409
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +52
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +127
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436
System.Web.Mvc.<>c__DisplayClassf.<InvokeActionMethodWithFilters>b__c() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +690
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +194

在调试器中执行该过程之后,我的ObjectContext(HGEntities)连接保持不变,直到我的视图模型 - &gt;调用游戏地图。由于某种原因,连接处于该点。关于为什么会发生这种情况的任何想法?

3 个答案:

答案 0 :(得分:1)

我发现IDisposable没有正确实现。也许这可能是你处理相关例外的原因?

答案 1 :(得分:0)

基于documentation,他们实际上不鼓励你使用工厂。我使用它们但它现在可能解决你的问题。我在ninject之旅的DI中得到了这个错误,但是很难说你为什么要得到你的错误。对我来说,这是由关系和延迟加载引起的。启用延迟加载后,对象将保持对ObjectContext的引用,以便它们可以填充相关对象和相关对象的集合。

最重要的是,我认为如果你发布错误的堆栈跟踪会有所帮助,所以我们可以帮助你确切知道它何时发生。

希望这有帮助。

编辑:我认为问题出在你的保存方法中。如果在游戏编辑时丢弃了对象上下文。我不认为它会在ObjectStateManager中看到你的行:

_context.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);

您从AutoMapper获取的当前游戏对象未附加到任何ObjectContext。这是我用于更新的方法:

public void Update(TEntity entity)
{
    object originalItem;

    EntityKey key = Context.CreateEntityKey(Context.GetEntitySet<TEntity>().Name, entity);

    if (Context.TryGetObjectByKey(key, out originalItem))
    {
        Context.ApplyCurrentValues(key.EntitySetName, entity);
    }
}

不要忘记致电Context.SaveChanges();

我没想出来,我自己发现它在网上的某个地方。它对我有用。我会调整你的保存方法来合并它。如果您需要帮助,请告诉我。我建议的另一件事(小)是在您的dispose方法中将您的Object上下文设置为null。

祝你好运!

编辑:好的,另一次尝试......基于管理控制器的构造函数,您的存储库是否有私有变量?

private IGameRepository _gameRepository;

public AdminController(IArticleRepository articleRepository, IGameRepository gameRepository, INewsRepository newsRepository)
    {
        _articleRepository = articleRepository;
        _gameRepository    = gameRepository;
        _newsRepository    = newsRepository;

控制器是否由ninject创建?我没有在绑定列表中看到AdminController。我没有在任何构造函数上看到[Inject]属性。当你发布到堆栈或者他们不在那里时你是否省略了它?

我的另一个想法是,如果您没有任何内存问题(泄漏)应用程序InSingletonScope()为您的上下文可能是适当的答案。

很抱歉所有的问题,但我只是想更好地了解这个问题。

答案 2 :(得分:0)

我自己的静态映射器完美运行:

public static class GameMapper
{
    public static Game MapFromEditModelToGame(IGameRepository repo, AdminGameViewModel formData, Game newGame)
    {
        newGame.GameID = formData.GameID;
        newGame.GameTitle = formData.GameTitle;
        newGame.GenreID = formData.GenreID;
        newGame.LastModified = DateTime.Now;
        newGame.ReviewScore = (short)formData.ReviewScore;
        newGame.ReviewText = formData.ReviewText;
        newGame.Cons = String.Join("|", formData.Cons);
        newGame.Pros = String.Join("|", formData.Pros);
        newGame.Slug = formData.Slug;

        if (newGame.Platforms != null && newGame.Platforms.Count > 0)
        {
            var oldPlats = newGame.Platforms.ToArray();

            foreach (var oldPlat in oldPlats)
            {
                newGame.Platforms.Remove(oldPlat);
            }
        }

        foreach (var platId in formData.PlatformIDs)
        {
            var plat = repo.GetPlatform(platId);
            newGame.Platforms.Add(plat);
        }

        return newGame;
    }
}

调用为:

game = GameMapper.MapFromEditModelToGame(_gameRepository, formData, game);

将上述内容与我的AutoMapper地图定义进行比较:

Mapper.CreateMap<AdminGameViewModel, Game>()
.BeforeMap((s, d) =>
{
    if (d.Platforms != null && d.Platforms.Count > 0)
    {
        var oldPlats = d.Platforms.ToArray();

        foreach (var oldPlat in oldPlats)
        {
            d.Platforms.Remove(oldPlat);
        }
    }

    foreach (var platId in s.PlatformIDs)
    {
        var plat = _gameRepository.GetPlatform(platId);
        d.Platforms.Add(plat);
    }
})
.ForMember(dest => dest.Platforms, opt => opt.Ignore())
.ForMember(dest => dest.BoxArtPath, opt => opt.Ignore())
.ForMember(dest => dest.IndexImagePath, opt => opt.Ignore())
.ForMember(dest => dest.Cons, opt => opt.MapFrom(src => string.Join("|", src.Cons)))
.ForMember(dest => dest.Pros, opt => opt.MapFrom(src => string.Join("|", src.Pros)))
.ForMember(dest => dest.LastModified, opt => opt.UseValue(DateTime.Now));

唯一真正的区别在于我将回购作为一个论据传递。

所有其他代码 - 我的控制器,我的DI内容等 - 完全相同。 唯一的区别在于我使用自己的cludgy mapper。不是理想的情况,而是一些东西。