2014-06-22 18 views

回答

2

TransactionHandler也適用於ObjectContext。唯一的問題是在實例化第一個DbContext之前,不會評估基於代碼的配置(DbConfiguration)。

兩個可能的解決方法

假的DbContext:

public class MyDbConfiguration : DbConfiguration 
{ 
    public MyDbConfiguration() 
    { 
     SetTransactionHandler(SqlProviderServices.ProviderInvariantName, 
      () => new CommitFailureHandler()); 
    } 
} 

public class TestContext : DbContext { } 

static void Main(string[] args) 
{ 
    // instantiate DbContext to initialize code based configuration 
    using (var db = new TestContext()) { } 

    using (var db = new TransactionHandlerDemoEntities()) { 
     var handler = db.TransactionHandler; // should be CommitFailureHandler 

     db.AddToDemoTable(new DemoTable { Name = "TestEntiry1" }); 
     db.SaveChanges(); 
    } 
} 

或者DbConfiguration.Loaded事件

static void Main(string[] args) 
{ 
    DbConfiguration.Loaded += DbConfiguration_Loaded; 

    using (var db = new TransactionHandlerDemoEntities()) { 
     var handler = db.TransactionHandler; 

     db.AddToDemoTable(new DemoTable { Name = "TestEntiry1" }); 
     db.SaveChanges(); 
    } 
} 

static void DbConfiguration_Loaded(object sender, DbConfigurationLoadedEventArgs e) 
{ 
    e.AddDependencyResolver(new TransactionHandlerResolver(
     () => new CommitFailureHandler(), 
     SqlProviderServices.ProviderInvariantName, 
     null),true); 
} 

TransactionHandlerDemoEntities是ObjectContext的。

+1

什麼想法使用虛擬DbContext! +1儘管我仍然認爲人們應該儘可能快地嘗試移動到DbContext API(就像我最近在應用程序中完成的那樣)。 –

+0

@GertArnold我完全同意。如果可能,移動到DbContext。如果沒有,我個人會去DbConfiguration.Loaded事件解決方法;-) – codeworx

0

這是專門爲DbContext。如果可以的話,儘快將基於ObjectContext的應用程序重構爲DbContext。我認爲還會有更多新功能出現,只適用於DbContext API。也許ObjectContext有時候甚至會被棄用爲公共API。

你可以create a DbContext from an ObjectContext,但我認爲這對你沒什麼幫助。主要的問題無疑是數據邏輯的其餘部分目前預計爲ObjectContext