繁体   English   中英

Linq to SQL,InsertOnSubmit vs. InsertAllOnSubmit性能?

[英]Linq to SQL, InsertOnSubmit vs. InsertAllOnSubmit performance?

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

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

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

两者中哪一个更好,两个代码片段与数据库的访问次数是否相同,因为在第一个片段提交更改是在循环之外调用的?

完全没有区别,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添加多个实体。 添加后我可以一次性提交更改,避免任何多个数据库调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM