【发布时间】:2013-06-20 09:19:16
【问题描述】:
两者在性能上是否存在巨大差异,比如我有这两个代码sn-ps:
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();
}
两者中哪一个更好?两个代码 sn-p 访问数据库的次数是否相同,因为在第一个 sn-p submitchanges 是在循环外调用的?
【问题讨论】:
-
您可以自己轻松地检查它,将日志机制添加到您的
context:damieng.com/blog/2008/07/30/… -
据我所知,InsertAllOnSubmit 仅迭代 IEnumerable 并为每个元素调用 InsertOnSubmit。在循环内部或外部调用 SubmitChanges 很重要,因为每个 SubmitChanges 调用都会打开一个新的事务/连接。
标签: c# sql linq linq-to-sql