I'd like to know if there's an easier way to batch insert a set of records if they don't already exist in a table. For example I have a Tags table in the database having ID, Name columns - given a list of tag names I want to add only those that are not already present. Here's what I came up with:
private static void InsertTags(IEnumerable<string> tagNames)
{
MyDataContext db = new MyDataContext();
var tags = from tagName in tagNames
where (db.Tags.Where(tag => tagName == tag.Name).FirstOrDefault() == null)
select new Tag
{
Name = tagName
};
db.Tags.InsertAllOnSubmit(tags);
}
Is there a better approach?