【问题标题】:Entity Framework 4 CTP 5 POCO - Insert multiple rows to a lookup table?Entity Framework 4 CTP 5 POCO - 将多行插入查找表?
【发布时间】:2011-01-29 10:35:45
【问题描述】:

如何使用 EF 在查找表中插入多行而不收到此错误:New transaction is not allowed because there are other threads running in the session

我有一个 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();
    }
}

谢谢。

【问题讨论】:

    标签: entity-framework-4 insert poco


    【解决方案1】:

    嘿 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();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多