0

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.

Community
  • 1
  • 1
Saxman
  • 5,009
  • 11
  • 51
  • 72

1 Answers1

0

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:

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

or

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

or

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

_postRepository.Add(post);
_unitOfWorkCommit();
Paul
  • 12,392
  • 4
  • 48
  • 58
  • Hi Paul, I was having problems with a many-to-many relationship with EF so I've decided to go with a lookup table. Here are my original questions regarding many-to-many as well as my problem: http://stackoverflow.com/questions/4571188/entity-framework-4-many-to-many-insertion and http://stackoverflow.com/questions/4589258/entity-framework-4-ctp-5-poco-many-to-many-or-lookup-table . – Saxman Jan 30 '11 at 17:11