我是 Entity Framework 的初学者,所以请多多包涵……
如何将来自不同上下文的两个对象关联在一起?
下面的示例引发以下异常:
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));
}
我已经阅读了很多关于这个异常的帖子,但没有一个给我一个有效的答案......
最佳答案
您的各种存储库_userRepository
, _blogEntryRepository
, _tagRepository
似乎都有自己的ObjectContext。您应该重构它并在存储库之外创建 ObjectContext,然后将其作为参数注入(inject)(对于所有存储库相同的 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
}
关于asp.net-mvc - 无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象mvc 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5538933/