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

标签 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();
}

对比

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/

相关文章:

c# - 将列表 <string> 传递到 Linq

c# - 我可以使用什么强类型数据结构来保存具有不同形状的多个 RecordSet 的集合

c# - 读写二进制文件的最快方法

c# - 如何正确地将CRLF(Environment.NewLine)添加到FileStream中?

sql - 将 R Dataframe 中的多行插入 Oracle 数据库

c# - ServiceStack Linq 合并字段和部分更新

linq - 您可以不使用连接语句将此 Linq 语句转换为 Lambda 吗?

c# - 无法附加已存在的实体

sql - 删除 SQL 注释

mysql - 在mysql数据库中存储泰卢固语文本时显示特殊字符