不能被限定的两个对象之间的关系,因为它们连接到不同的ObjectContext对象MVC 2 [英] 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:无法定义的两个对象之间的关系,因为它们连接到不同的ObjectContext对象。
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...
推荐答案
您各种信息库 _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:
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
}
这篇关于不能被限定的两个对象之间的关系,因为它们连接到不同的ObjectContext对象MVC 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!