两者在性能上是否有很大差异,例如我有这两个代码片段:
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();
}
对比
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();
}
两者中哪一个更好,两个代码片段访问数据库的次数是否相同,因为在第一个片段中 submitchanges 是在循环外调用的?
最佳答案
完全没有区别,InsertAllOnSubmit实际上调用了InsertOnSubmit,这里是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);
}
}
}
如您所见,InsertAllOnSubmit 只是一个方便的 InsertOnSubmit 包装器
关于c# - Linq to SQL、InsertOnSubmit 与 InsertAllOnSubmit 性能对比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17209893/