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

691*_*138 6 linq asp.net-mvc entity-framework asp.net-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)

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

Sla*_*uma 7

你的各种信息库_userRepository,_blogEntryRepository,_tagRepository似乎有自己所有的ObjectContext.您应该重构它并在存储库之外创建ObjectContext,然后将其作为参数注入(对于所有存储库,使用相同的ObjectContext),如下所示:

public class XXXRepository
{
    private readonly MyObjectContext _context;

    public XXXRepository(MyObjectContext context)
    {
        _context = context;
    }

    // Use _context in your repository methods.
    // Don't create an ObjectContext in this class
}
Run Code Online (Sandbox Code Playgroud)