我已經調用Membership API和角色API在相同的事務範圍。我讀過打開多個連接導致升級需要啓用分佈式事務,所以我正在尋找一種方法來打開一個連接並與之共享:成員資格,角色,我自己的調用。TransactionScope與成員資格和角色調用在同一個塊(只使用一個連接的方式?)
這裏是工作的代碼,導致不必要的升級:
public static void InsertUser(string userName, string email, string roleName, int contactId, string comment)
{
/*
* Exceptions thrown here are caught in the DetailView's event handler and piped to the UI.
*/
using(var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
string password = Membership.GeneratePassword(Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters);
const string passwordQuestion = "Should you change your password question?";
const string passwordAnswer = "yes";
MembershipCreateStatus status;
MembershipUser user = Membership.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, true, out status);
if(user == null)
{
throw new Exception(GetErrorMessage(status));
}
// Flesh out new user
user.Comment = comment;
Membership.UpdateUser(user);
// Give user a role
Roles.AddUserToRole(user.UserName, roleName);
// Create bridge table record
Guid userId = (Guid)ExceptionUtils.ThrowIfDefaultValue(user.ProviderUserKey, "ProviderUserkey is null!");
insertIntoAspnet_Users_To_Contact(userId, contactId);
// Send welcome email
EmailUtils.SendWelcomeEmailFromAdmin(userName, email, password, passwordQuestion, passwordAnswer, roleName);
transactionScope.Complete();
}
}
感謝
是否將您的數據庫連接設置爲池?如果是這樣,底層連接將保持打開幾秒鐘,看看你是否會提出額外的請求。如果是,即使使用新的連接對象,它也會使用相同的連接。這一切都歸結爲我相信的連接池。 – 2011-06-06 20:55:37