Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I beginners to the entity framework, so please bear with me...

How can I relate two objects from different contexts together?

The example below throws the following exception:

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

    [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));             
    }

I've read a lot of posts about this exception but none give me a working answer...

like image 581
691138 Avatar asked Apr 04 '11 13:04

691138


1 Answers

Your various repositories _userRepository, _blogEntryRepository, _tagRepository seem to have all their own ObjectContext. You should refactor this and create the ObjectContext outside of the repositories and then inject it as a parameter (for all repositories the same ObjectContext), like so:

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
}
like image 104
Slauma Avatar answered Nov 14 '22 12:11

Slauma