Ran*_*rez 9 c# sql linq linq-to-sql
两者之间的性能是否存在巨大差异,例如我有这两个代码片段:
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();
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
两者中哪一个更好,两个代码片段与数据库的访问次数是否相同,因为在第一个片段提交更改是在循环之外调用的?
Ale*_*iuc 16
完全没有区别,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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,InsertAllOnSubmit只是InsertOnSubmit的一个方便的包装器