Error when Inserting using SqlMapperExtension Dapper

c# dapper dapper-extensions insert

Question

Currently playing around with Dapper I'm trying to insert values into the db as follows

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();
    }
}

The error I get is

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. 

I have googled this error, but I misunderstood the answers provided.

Popular Answer

From the error message I assume that you have started a transaction that was neither committed nor rolled back. The real cause for this error message is elsewhere.

I suggest you to log requests in Context.ReturnDatabaseConnection() and trace what requests precede this error.

Also I advice you to look in your code for all transactions and check if they are correctly completed (commit/rollback).




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why