如何在没有收到此错误的情况下向EF的查找表中插入多行:New transaction is not allowed because there are other threads running in the session
?
我有一个PostTags查找表,其中我的许多标签可以来自帖子,这是我目前拥有的更新方法,错误似乎来自我插入标签的foreach
循环(I我在这篇文章中使用了工作单元,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 :(得分:0)
嘿Saxman - 我还没有看过你的模型,但是使用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();