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...
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With