2011-01-28 62 views
0

如何將多行插入EF查找表而不會收到此錯誤:New transaction is not allowed because there are other threads running in the session實體框架4 CTP 5 POCO - 將多行插入查找表?

我有一個PostTags查找表,其中我有很多標籤可以從一個帖子,這是我目前有我的更新方法,錯誤似乎來自foreach循環插入標籤(我正在使用在這個崗位工作單元,POCO的,EF 4 cpt5存儲庫模式 - Entity Framework 4 CTP 4/CTP 5 Generic Repository Pattern and Unit Testable):

if (ModelState.IsValid) 
{ 
    post.FriendlyUrl = Utils.ToFriendlyUrl(post.PostedDate.ToString("yyyy/MM/dd") + "/" + Utils.RemoveAccents(post.Title)); 
    var tags = post.TagsString.TrimEnd(' ', ',').Split(',').ToList(); 

    var updatePost = Mapper.Map<PostModel, Post>(post); 

    var postTags = new List<int>(); 
    foreach (var tag in tags) 
    { 
     postTags.Add(_tag.CheckExistingTag(tag.Trim())); 
    } 

    _post.UpdatePost(updatePost); 
    _unitOfWork.Commit(); 

    // Remove all existing tags associated with this post 
    _postTag.RemoveAllTagsInPost(updatePost.Id); 

    // Insert to the PostTagLookup table the new Tags that associates with this Post 
    foreach (var tagId in postTags) 
    { 
     var newPostTag = new PostTagLookup { PostId = updatePost.Id, TagId = tagId }; 
     _postTag.Add(newPostTag); 
     _unitOfWork.Commit(); 
    } 
} 

感謝。

回答

0

嘿薩克斯曼 - 我還沒有看到你的模型,但用EF你不需要擔心查找表,EF會爲你做映射!

所以,你可以做這樣的事情:

var post = new post(); 
post.Tags.Add(new Tag()); 
_postRepository.Add(post); 
_unitOfWorkCommit(); 

var post = new post(); 
var tags = new List<Tag>{new Tag {Post = post}, new Tag {Post = post}}; 
_postRepository.Add(post); 
_unitOfWorkCommit(); 

var post = new post(); 
var tags = GetTagList(); 
foreach(var tag in tags) { 
    post.Tags.Add(tag); 
} 

_postRepository.Add(post); 
_unitOfWorkCommit(); 
+0

保羅嗨,我是有問題多到許多與關係EF,所以我決定去查找表。這裏是我關於多對多以及我的問題的原始問題:http://stackoverflow.com/questions/4571188/entity-framework-4-many-to-many-insertion和http://stackoverflow.com/questions/4589258/entity-framework-4-ctp-5-poco-many-to-many-lookup-table。 – Saxman 2011-01-30 17:11:04