问题尝试一个新的实体EF4附加到ObjectContext的,而其单位收藏单位已经连接 [英] Problems trying to attach a new EF4 entity to ObjectContext while its entity collection entities are already attached

查看:234
本文介绍了问题尝试一个新的实体EF4附加到ObjectContext的,而其单位收藏单位已经连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有些复杂解释,所以请多多包涵。

This is somewhat complicated to explain, so please bear with me.

我有一个ASP.NET MVC 2项目的<击>正在慢慢杀死我中,我试图把表单数据,并将其转化为实体创建或更新,根据的情况下情况。最相关的部分(伪code):

I have an ASP.NET MVC 2 project that is slowly killing me in which I'm trying to take form data and translate it into entities to create or update, depending on the context of the situation. The most relevant parts (pseudo-code):

Entity Game
    Scalar properties
    EntityCollection<Platform> Platforms

和基本的工作流程是:

表单数据 - >模型绑定到一个DTO - >映射DTO与AutoMapper一个EF4实体

Form data -> model bound to a DTO -> mapping the DTO to an EF4 entity with AutoMapper.

这一切都只有一个例外效果很好 - 我需要创建或更新游戏实体与包含在DTO的原始整数索引数据平台EntityCollection。所以,在这里就是我一直很努力,这不工作:

It all works well with one exception - I need to create or update the Game entity's Platforms EntityCollection with the raw integer index data contained in the DTO. So, here's what I've been trying, which does not work:

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

    Mapper.CreateMap<AdminGameEditModel, Game>()
        .BeforeMap((s, d) =>
        {
            if (d.Platforms.Count > 0)
            {
                Platform[] existing = d.Platforms.ToArray();

                foreach (var plat in existing)
                {
                    d.Platforms.Remove(plat);
                }
            }

            foreach (var platId in s.PlatformIDs)
            {
                var newPlat = _gameRepository.GetPlatform(platId);

                d.Platforms.Add(newPlat); // <-- where it chokes
            }
        })
        .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))
        .ForMember(dest => dest.Platforms, opt => opt.Ignore());
}

要具体,我发现了一个例外,在我上面其中强调该行称:

To be specific, I'm getting an exception at the line I highlighted above which says:

两个对象之间的关系不能被限定,因为它们连接到不同的ObjectContext对象

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

一些研究告诉我,这是可以预料的,因为我的新鲜游戏对象没有,它的关联ObjectContext的,和一个空的上下文被认为是一个单独的上下文。看到朱莉·勒曼了解这个简短的解释更多。

Some research tells me that this is to be expected, as my fresh Game object has no ObjectContext that it's associated with, and a null context is considered to be a separate context. See this brief explanation from Julie Lerman for more.

好吧,是勇敢的人,我,我想我会简单地可以注册自己的比赛与ObjectContext的一切将被修复。所以,我想:

Okay, so being the intrepid person I am, I figured I would simply be able to register my game with the ObjectContext and everything would be fixed. So, I tried:

Game game = new Game();
_gameRepository.RegisterGame(game);

在哪里RegisterGame很简单:

Where RegisterGame is simply:

public void RegisterGame(Game game)
{
    _siteDB.Games.AddObject(game);
}

不幸的是,没有工作。同样的异常是在同一时间点抛出。

Unfortunately, that did not work. The same exception is being thrown at the same point.

所以,它看起来像我将不得不每个平台的的EntityKey添加到我的EntityCollection。唯一的问题是,我不知道该怎么做。

So, it looks like I'll have to add each Platform's EntityKey to my EntityCollection. Only problem is, I'm not sure how to do it.

所以,任何想法?

编辑:一种进展。我尝试添加该平台的实体正好EntityKeys,像这样:

Progress of a sort. I tried adding just the EntityKeys of the Platform entities, like so:

Mapper.CreateMap<AdminGameEditModel, Game>()
    .BeforeMap((s, d) =>
    {
        if (d.Platforms.Count > 0)
        {
           Platform[] existing = d.Platforms.ToArray();

           foreach (var plat in existing)
           {
                d.Platforms.Remove(plat);
           }
        }

        foreach (var platId in s.PlatformIDs)
        {
            var newPlat = _gameRepository.GetPlatform(platId);

            d.Platforms.Add(new Platform { EntityKey = newPlat.EntityKey });
        }
    })

和它消除了两种不同的ObjectContexts'例外。问题是,我得到了以下异常,如果我尝试添加或新的游戏实体附加到我的上下文:

And it removes the 'two different ObjectContexts' exception. The problem is that I'm getting the following exception if I try to add or attach the new Game entity to my context:

具有相同键的对象已经存在于ObjectStateManager。该ObjectStateManager无法跟踪多个对象使用相同的密钥。

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

不幸的是,除了没有指定的对象是的,但我打赌它的平台的一个对象,因为它们已经存在,我只是试图建立一种新的关系在两者之间。

Unfortunately, the exception doesn't specify which object it is, but I'm betting it's one of the Platform objects, since they already exist and I'm merely trying to forge a new relationship between the two.

所以,问题是:到底如何做一件让一个新的实体,填充它的EntityCollection&LT;>与现有实体的财产?我不能成为谁曾经想创建一个新的实体,创建与现有实体之间的新多到许多关系的唯一的人,对吧?

So, the question remains: how the hell does one make a new entity and populate its EntityCollection<> property with existing entities? I can't be the only person who ever wanted to create a new entity and create new many-to-many relationships between it and existing entities, right?

推荐答案

我把它用<一工作href=\"http://stackoverflow.com/questions/4764370/problems-updating-w-ef4-repo-mvc2-cant-update-many-to-many-graph/4764497#4764497\">Julie勒曼的原液。我没有分离/再附上我的平台我原来的,pre-DTO的解决方案,所以我想我没必要在这里。在任何情况下,它看起来像我需要做如何处理ObjectContext的更多的研究。

I got it to work by using Julie Lerman's original solution. I didn't have to detach/re-attach my platforms with my original, pre-DTO solution, so I thought I didn't need to here. In any event, it looks like I need to do more research on how to handle the ObjectContext.

这篇关于问题尝试一个新的实体EF4附加到ObjectContext的,而其单位收藏单位已经连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆