2011-04-04 9 views
6

I初心者のオブジェクト異なるのObjectContextに添付されているので、2つのオブジェクト間の関係を定義することはできません一緒に?彼らはので、私は別の文脈から2つのオブジェクトを関連付けることができますどのように...私と一緒に</p> <p>をご負担ください、エンティティフレームワークにMVC 2つの

以下の例は、次の例外をスロー:

のSystem.InvalidOperationException:それらが異なるのObjectContextオブジェクトに取り付けられているので、2つのオブジェクト間の関係を定義することができません。私はこの例外についての記事をたくさん読みましたが、どれも私の作業答えを与えない

[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));    
    } 

...

答えて

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 
} 
+0

追加@にSlaumaの答えを:あなたは添付オブジェクトを関連付けることができません異なる文脈に唯一の方法は、最初のコンテキストからオブジェクトを切り離して、それを2番目のコンテキストにアタッチすることです。リポジトリ間でコンテキストを共有するのははるかに複雑です。 –

関連する問題