2011-01-28 90 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