实体框架 4 CTP 5 POCO - 将多行插入查找表?
如何使用 EF 将多行插入到查找表中而不收到此错误:不允许新事务,因为会话中正在运行其他线程
?
我有一个 PostTags 查找表,其中许多标签可以来自帖子,这就是我目前的更新方法,错误似乎来自我插入标签的 foreach
循环(我在这篇文章中使用工作单元、poco、ef 4 cpt5 存储库模式 - 实体框架 4 CTP 4 / CTP 5 通用存储库模式和可单元测试):
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();
}
}
谢谢。
How would I insert multiple rows to a lookup table with EF without receiving this error: New transaction is not allowed because there are other threads running in the session
?
I have a PostTags lookup table where I many tags can be from a post, this is what I currently have for my update method, the error seems to come from the foreach
loop where I insert the tags (I'm using unit of work, poco, ef 4 cpt5 repository pattern in this post - 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();
}
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嘿 Saxman - 我还没有见过你的模型,但是使用 EF,你不需要担心查找表,EF 会为你做映射!
所以你可以做这样的事情:
或
或
Hey Saxman - I have not seen your Model, but with EF you do not need to worry about the look up table, EF will do the mapping for you!
So you can do something like this:
or
or