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

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的方便包装器

09-16 10:16