开发者

I get the error : “An entity object cannot be referenced by multiple instances of IEntityChangeTracker.” with .net MVC2 and the Entity Framework4

I have a big problem since some days and I’m a very beginner in the Entity Framework. I have 2 entities : Group and News. A news is visible by one or many groups. I use two repositories (newsRepository and groupsRepository).

This is my Create method for the news :

    public ActionResult Create()
    {
        return View(new CreateNewsViewModel(new News()));
    }

    [HttpPost]
    public ActionResult Create(CreateNewsViewModel model)
    {
        model.news.CategoryId = Int32.Parse(Request.Form["news.CategoryId"]);

        if (ModelState.IsValid)
        {
            News news = new News();

            DateTime date = DateTime.Now;

            //AuthorId a recuperer
            news.AuthorId = 1;
            news.Title = IntranetTools.UppercaseFirst(model.news.Title.Trim());
            news.Content = model.news.Content;
            news.IsVisible = Request.Form["news.IsVisible"].Contains("true");
            news.CreateDate = date;
            news.PublicationDate = date;
            news.LastChangedDate = date;
            news.CategoryId = model.news.CategoryId;

            // Collection des groupes concernés
            foreach (var c in model.allGroups)
            {
                if (Request.Form["" + c.GroupId].Contains("true"))
                {
                    News.Groups.Add(c);
    开发者_JAVA技巧            }
            }

            _newsRepository.AddToNewsSet(news);
            _newsRepository.SaveChanges();

            return Redirect("/NewsAdmin/Index/");
        }
        return View(model);
    }

I say that all my groups are already created. I just want to insert the groups (chosen by the user via checkboxes). In my “CreateNewsViewModel”, I create a list of groups that contains all existing groups in my DB. I get the list in my view, via a “foreach” loop and create a checkbox for each group.

I reuse the same list in my controller to compare if checkboxes have been checked. For each “true” value, I add groups in the groups collection of my news (just created).

With this, I get this Error Message :

“An entity object cannot be referenced by multiple instances of IEntityChangeTracker.” (at line _newsRepository.AddToNewsSet(news);)

I try some solutions but I still don’t understand how I can solve this problem.

Thanks for all


Edit

Actually, if I use explicitly two contexts and detach/attach my objects to other context it's fine and I have no erros.

            ObjectContext context  = _newsRepository.Context;
            ObjectContext context2 = _groupsRepository.Context;

            foreach (var c in groups)
            {
                if (Request.Form["" + c.GroupId].Contains("true"))
                {
                    context2.Detach(c);
                    context.Attach(c);
                    news.Groups.Add(c);
                }
            }

I would like to use the Ladislav Mrnka's solution and use the dependency injection (I use Ninject framework) to give the same ObjectContext to my repositories (in single request processing). I understand the concept but I don't know how to code it.


The error message says that News object or any of related Group objects is attached to different ObjectContext instance. How is your repository implemented and how did you get model.allGroups? If you loaded allGroups from GroupsRepository which has its own ObjectContext instance then it is probably source of the problem. The solution would be:

  • (Preferred) Share single ObjectContext for all repositories in single request processing
  • Detach objects when you load them from database (ObjectContext has Detach method)
  • Close ObjectContext when you load objects from database
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜