It is my understanding that to easily add a list of objects to the database you can add them to a list and then simply call the AddRange followed by the SaveChanges to get this accomplished in one query. We are using a profiler however and seeing it turn all of our items in the list into separate insert statements.
Is my thinking wrong about how AddRange works or is there some other issue? I really thought I would see one single insert statement instead of however many items were in the list.
In the code below we are adding a LearningPath and then adding lessons to this learning path. At first I thought it may have something to do with each LearningPathLesson querying to find the LessonPathId, however when I moved that around it still didn't fix the issue.
public static void SaveLearningPath(LearningPathSaveModel model)
{
using (var db = new ServerDBEntities())
{
var now = DateTimeOffset.Now;
var learningPath = new LearningPath()
{
Id = string.IsNullOrEmpty(model.id) ? Guid.NewGuid().ToString() : model.id,
Name = model.name,
Created = now,
Updated = now
};
if (model.defaultLearningPath)
{
learningPath.IsDefault = true;
var previousDefault = db.LearningPaths.FirstOrDefault(l => l.IsDefault == true);
if (previousDefault != null)
{
previousDefault.IsDefault = false;
}
}
db.LearningPaths.Add(learningPath);
db.SaveChanges();
string lpId = learningPath.Id;
var learningPathLessons = new List<LearningPathLesson>();
for (var i = 0; i < model.lessonIdsInLearningPath.Count; ++i)
{
var id = model.lessonIdsInLearningPath[i];
learningPathLessons.Add(new LearningPathLesson()
{
Id = Guid.NewGuid().ToString(),
LessonId = id,
LearningPathId = lpId,
Order = i + 1,
Created = now,
Updated = now
});
}
//db.LearningPaths.Add(learningPath);
db.LearningPathLessons.AddRange(learningPathLessons);
db.SaveChanges();
}
}