如何为 ObjectContext 设置 TransactionHandler?
我正在检查这个例子:Handling of Transaction Commit Failures ,但仅针对 DbContext 显示。
最佳答案
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。
关于c# - ObjectContext 的 SetTransactionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24355314/