Linq to SQL, InsertOnSubmit and InsertAllOnSubmit?

Is there a performance difference between the two, for example, I have these two code snippets:

public void Insert(IEnumerable<ManageGeofenceViewModel> geofences) { var insertGeofences = new List<Geofence>(); foreach(var geofence in geofences) { Geofence insertGeofence = new Geofence { name = geofence.Name, radius = geofence.Meters, latitude = geofence.Latitude, longitude = geofence.Longitude, custom_point_type_id = geofence.CategoryID }; insertGeofences.Add(insertGeofence); } this.context.Geofences.InsertAllOnSubmit(insertGeofences); this.context.SubmitChanges(); } 

vs

 public void Insert(IEnumerable<ManageGeofenceViewModel> geofences) { foreach(var geofence in geofences) { Geofence insertGeofence = new Geofence { name = geofence.Name, radius = geofence.Meters, latitude = geofence.Latitude, longitude = geofence.Longitude, custom_point_type_id = geofence.CategoryID }; this.context.Geofences.InsertOnSubmit(insertGeofence); } this.context.SubmitChanges(); } 

Which of the two options is better, and the two code snippets have the same number of trips to the database, since in the first snippet snippet is called outside the loop?

+6
source share
2 answers

It makes no difference, InsertAllOnSubmit actually calls InsertOnSubmit, here is the code for InsertAllSubmit:

 public void InsertAllOnSubmit<TSubEntity>(IEnumerable<TSubEntity> entities) where TSubEntity : TEntity { if (entities == null) { throw Error.ArgumentNull("entities"); } this.CheckReadOnly(); this.context.CheckNotInSubmitChanges(); this.context.VerifyTrackingEnabled(); List<TSubEntity> list = entities.ToList<TSubEntity>(); using (List<TSubEntity>.Enumerator enumerator = list.GetEnumerator()) { while (enumerator.MoveNext()) { TEntity entity = (TEntity)((object)enumerator.Current); this.InsertOnSubmit(entity); } } } 

As you can see, InsertAllOnSubmit is just a handy wrapper around InsertOnSubmit

+13
source

You can find many convenient methods, such as focusing on coding efficiency. If you have a list of objects that you want to insert into the database immediately, you can use InsertAllOnSubmit . Below is an example from one of my projects.

 public void InsertAll(IEnumerable<MyClass> list) { DataContext.MyClasses.InsertAllOnSubmit<MyClass>(list); DataContext.SubmitChanges(); } 

This code allows me to add multiple objects to a DataContext using a single line. After adding, I can send the changes in one go, avoiding any calls with multiple databases.

-1
source

Source: https://habr.com/ru/post/947718/


All Articles