2014年3月21日 星期五

SqlException from Entity Framework

在Foreach中加入 Entity framework 的SaveChanges 出現這個錯誤:

"New transaction is not allowed because there are other threads running in the session"

可以參考這篇微軟的回答

解決方式請參考  ~

(以下內容為轉貼 stackoverflow)

// 1: Save after iteration (recommended approach in most cases)
using (var context = new MyContext())
{
    foreach (var person in context.People)
    {
        // Change to person
    }
    context.SaveChanges();
}

// 2: Declare an explicit transaction
using (var transaction = new TransactionScope())
{
    using (var context = new MyContext())
    {
        foreach (var person in context.People)
        {
            // Change to person
            context.SaveChanges();
        }
    }
    transaction.Complete();
}


沒有留言:

張貼留言