无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象 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));
}
我读过很多关于这个例外的帖子,但没有一个给我一个有效的答案......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的各种存储库
_userRepository
、_blogEntryRepository
、_tagRepository
似乎都有自己的 ObjectContext。您应该重构它并在存储库外部创建 ObjectContext,然后将其作为参数注入(对于所有存储库相同的 ObjectContext),如下所示: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: