小编691*_*138的帖子

无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象mvc 2

我是实体框架的初学者,所以请耐心等待...

如何将来自不同上下文的两个对象关联在一起?

以下示例引发以下异常:

System.InvalidOperationException:无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象.

    [OwnerOnly]
    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Create(BlogEntryModel model)
    {
        if (!ModelState.IsValid)
            return View(model);
        var entry = new BlogEntry
        {
            Title = model.Title,
            Content = model.Content,
            ModifiedDate = DateTime.Now,
            PublishedDate = DateTime.Now,
            User = _userRepository.GetBlogOwner()
        };
        _blogEntryRepository.AddBlogEntry(entry);
        AddTagsToEntry(model.Tags, entry);
        _blogEntryRepository.SaveChange();
        return RedirectToAction("Entry", new { Id = entry.Id });
    }

    private void AddTagsToEntry(string tagsString, BlogEntry entry)
    {
        entry.Tags.Clear();
        var tags = String.IsNullOrEmpty(tagsString)
                       ? null
                       : _tagRepository.FindTagsByNames(PresentationUtils.ParseTagsString(tagsString));
        if (tags != null)
            tags.ToList().ForEach(tag => entry.Tags.Add(tag));             
    }
Run Code Online (Sandbox Code Playgroud)

我已经阅读了很多关于这个例外的帖子,但没有一个给我一个有效的答案......

linq asp.net-mvc entity-framework asp.net-mvc-2

6
推荐指数
1
解决办法
5649
查看次数