gpt4 book ai didi

c# - Linq to SQL、InsertOnSubmit 与 InsertAllOnSubmit 性能对比?

转载 作者:太空狗 更新时间:2023-10-29 17:40:20 24 4
gpt4 key购买 nike

两者在性能上是否有很大差异,例如我有这两个代码片段:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com