最近我遇到了一个小故障,同时试图将一些涉及WebSecurity和DbContext的操作包含在事务中。
在我的Asp.net MVC 4应用程序中,我正在尝试以这种方式注册新用户:
var transactionOptions = new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted,
Timeout = TransactionManager.MaximumTimeout
};
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
var confirmationToken = WebSecurity.CreateUserAndAccount(
vm.Email,
vm.Password,
new
{
AccountCreationDate = DateTime.Now,
City = vm.City,
(...)
},
true);
Roles.AddUserToRole(vm.Email, "Client");
// Some other job on DbContext in Repository
var userRepository = new UserRepository();
userRepository.AssignData(vm.Email);
transactionScope.Complete();
}
var transactionOptions = new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted,
Timeout = TransactionManager.MaximumTimeout
};
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
var confirmationToken = WebSecurity.CreateUserAndAccount(
vm.Email,
vm.Password,
new
{
AccountCreationDate = DateTime.Now,
City = vm.City,
(...)
},
true);
Roles.AddUserToRole(vm.Email, "Client");
// Some other job on DbContext in Repository
var userRepository = new UserRepository();
userRepository.AssignData(vm.Email);
transactionScope.Complete();
}
正如您所看到的,我正在尝试创建用户帐户和成员资格条目,分配角色,然后通过存储库在EF5 DbContext上执行其他操作。
此代码包含在try-catch块中,为简洁起见,此处不再包含此内容。
这就是我的问题:是否可以通过一个事务将所有这3个命中包装到数据库(分别通过WebSecurity,Roles和Repository)而不允许它升级到DTC?
我正在使用SQL Server 2012,一个数据库和相同的连接字符串(如果有帮助的话)。