2014-11-21 41 views
1

我必須從電子表格導入大約30個數據缺失到MSSQL數據庫中。我使用實體框架插入/更新記錄到數據庫中。但默認的實體框架配置性能非常慢。約束是,我需要在插入表之前驗證記錄。如果它存在,那麼它應該用新值更新,否則它應該向數據庫中插入新記錄。但是,將記錄插入/更新到數據庫需要很長時間。我找到了一個解決方案來加速這個過程here實體框架Context.Configuration.AutoDetectChangesEnabled更新問題?

Context.Configuration.AutoDetectChangesEnabled = false; 

以上設置使速度有很大的差異。

但是大問題,當我將AutoDetectChangesEnabled設置爲false,但是inserting功能完全正常時,表中沒有更新記錄。

其他人看到這個問題?有人幫助解決這個問題嗎?

回答

0

我已通過使用下面的代碼解決了此問題。當AutoDetectChangesEnabled設置爲false時,entry.State變爲Unchanged

public virtual void Update(T entity) 
    { 
     //DbSet.Attach(entity); 
     //context.Entry(entity).State =EntityState.Modified; 


     if (entity == null) 
     { 
      throw new ArgumentException("Cannot add a null entity."); 
     } 

     var entry = context.Entry<T>(entity); 

     if (entry.State == EntityState.Detached) 
     { 
      var pkey = DbSet.Create().GetType().GetProperty(entity.GetType().Name + "ID").GetValue(entity); 

      var set = context.Set<T>(); 
      T attachedEntity = set.Find(pkey); // You need to have access to key 

      if (attachedEntity != null) 
      { 
       var attachedEntry = context.Entry(attachedEntity); 
       attachedEntry.CurrentValues.SetValues(entity); 
      } 
      else 
      { 
       entry.State = EntityState.Modified; // This should attach entity 
      } 
     } 
     else if (entry.State == EntityState.Unchanged) 
     { 
      entry.State = EntityState.Modified; 
     } 

    }`