簡體   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