views:

2684

answers:

1
  1. I have a Tags table whose schema consists of only ID and Name (unique). Now, from the GUI user can enter tags for a BlogPost. When the data is saved, with tags stored in an array of string (names), I want to add tags whose names don't yet exist to the Tag table and ignore tags whose names already exist AND get back the list of all tag entities (including the existing and newly added ones). How can I do this in Entity Framework in just 1 SQL roundtrip?

  2. For the returned tags, I want to associate them to the to-be-added BlogPost object (which is just instantiated and not stored in DB via EF yet). Is it still possible that this step can be combined with #1 in 1 single roundtrip or must I have to issue another query?

+1  A: 

I don't believe the Entity Framework does batch inserts at all (at present). So if you must keep the number of DB roundtrips so low, you're probably going to have to use a stored procedure or a database trigger. Fortunately, the Entity Framework supports stored procedures which return entity types. There is documentation on MSDN about this. You could create a proc which accepts a string list of tags and returns tag entity instances. Alternately, you could add a VARCHAR column to your post table for a delimited list of tags, and parse it in the trigger.

Craig Stuntz