【问题标题】:Linq to SQL, InsertOnSubmit vs. InsertAllOnSubmit performance?Linq to SQL,InsertOnSubmit 与 InsertAllOnSubmit 性能?
【发布时间】: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


【解决方案1】:

完全没有区别,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 的一个方便的包装器

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多