Linq to SQL, InsertOnSubmit vs. InsertAllOnSubmit performanc

本文关键字:vs InsertAllOnSubmit performanc InsertOnSubmit to SQL Linq | 更新日期: 2023-09-27 18:19:14

两者之间是否存在巨大的性能差异,例如我有这两个代码片段:

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 ?

Linq to SQL, InsertOnSubmit vs. InsertAllOnSubmit performanc

根本没有区别,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

的一个方便的包装

您可以找到许多这样的方便方法,这些方法专注于编码效率。如果您有一个想要立即插入到数据库中的实体列表,您可以使用InsertAllOnSubmit。下面是我的一个项目的例子。

public void InsertAll(IEnumerable<MyClass> list)
    {
        DataContext.MyClasses.InsertAllOnSubmit<MyClass>(list);
        DataContext.SubmitChanges();
    }

这段代码使我能够使用一行向DataContext添加多个实体。添加后,我可以一次提交更改,避免任何多个数据库调用。