2012-12-01 35 views
1

錯誤在於:模型創建時無法使用上下文。創建模型時無法使用上下文

我使用這個代碼:

Parallel.Invoke(AddDataParallel); 



    private void AddDataParallel() 
    { 
     Parallel.For(1001, 2001, delegate(int i) 
            { 
             User user = new User(); 
             user.UserName = "user" + i; 
             _userService2.Add(user); 
            }); 

    } 

錯誤:

public T Add(T entity) 
    { 
     return _entities.Add(entity);//The context cannot be used while the model is being created. 
    } 

爲什麼呢?

回答

0

您似乎只使用一個上下文實例(包裝在_userService2中)。但ObjectContext(或DbContext)按照MSDN不是線程安全的。請參閱備註:

ObjectContext類不是線程安全的。多線程場景中無法確保ObjectContext中數據對象的完整性。

所以你必須重新設計你的插入場景。對於一個數據庫來說,並行化是非常棘手的,因爲你讓自己成爲一個併發用戶。如果你想快速插入,看看BulkInsert

相關問題