使用SqlMapperExtension Dapper插入时出错

时间:2014-11-03 03:51:27

标签: c# insert dapper dapper-extensions

目前正在玩Dapper我试图将值插入数据库,如下所示

using (var sqlCon = new SqlConnection(Context.ReturnDatabaseConnection()))
{
    sqlCon.Open();

    try
    {
        var emailExists = sqlCon.Query<UserProfile>(@"SELECT UserId FROM User_Profile WHERE EmailAddress = @EmailAddress",
                          new { EmailAddress = userRegister.EmailAddress.Trim() }).FirstOrDefault();

        if (emailExists == null) // No profile exists with the email passed in, so insert the new user.
        {
            userProfile.UniqueId = Guid.NewGuid();
            userProfile.Firstname = userRegister.Firstname;
            userProfile.Surname = userRegister.Surname;
            userProfile.EmailAddress = userRegister.EmailAddress;
            userProfile.Username = CreateUsername(userRegister.Firstname);
            userProfile.Password = EncryptPassword(userRegister.Password);
            userProfile.AcceptedTerms = true;
            userProfile.AcceptedTermsDate = System.DateTime.Now;
            userProfile.AccountActive = true;
            userProfile.CurrentlyOnline = true;
            userProfile.ClosedAccountDate = null;
            userProfile.JoinedDate = System.DateTime.Now;

            userProfile.UserId = SqlMapperExtensions.Insert(sqlCon, userProfile); // Error on this line

            Registration.SendWelcomeEmail(userRegister.EmailAddress, userRegister.Firstname); // Send welcome email to new user.
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    finally
    {
        sqlCon.Close();
    }
}

我得到的错误是

ExecuteNonQuery requires the command to have a transaction when the connection 
assigned to the command is in a pending local transaction.  The Transaction 
property of the command has not been initialized. 

我用Google搜索了这个错误,但我误解了所提供的答案。

1 个答案:

答案 0 :(得分:0)

从错误消息中我假设您已经启动了既未提交也未回滚的事务。此错误消息的真正原因是其他地方。

我建议您在Context.ReturnDatabaseConnection()中记录请求并跟踪此错误之前的请求。

另外,我建议您查看代码中的所有事务并检查它们是否正确完成(提交/回滚)。