我是实体框架的初学者,所以请耐心等待......
如何将来自不同上下文的两个对象关联在一起?
以下示例引发以下异常:
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));
}
我已经阅读了很多有关此例外的帖子,但没有一个给我一个有效的答案......
答案 0 :(得分: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
}