Dapper .Net ExecuteNonQuery需要命令才能进行事务处理

时间:2014-11-14 06:35:21

标签: c# asp.net-mvc dapper dapper-extensions

按照代码插入记录,首先我检查以确保数据库中已存在电子邮件地址,如果确实如此,我会返回警告用户,否则我会插入新记录。

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

            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.
            {
                var userProfileEntity = new UserProfileEntity
                {
                    UniqueId = Guid.NewGuid(),
                    Firstname = userRegister.Firstname,
                    Surname = userRegister.Surname,
                    EmailAddress = userRegister.EmailAddress,
                    Username = CreateUsername(userRegister.Firstname),
                    Password = EncryptPassword(userRegister.Password),
                    AcceptedTerms = true,
                    AcceptedTermsDate = System.DateTime.Now,
                    AccountActive = true,
                    CurrentlyOnline = true,
                    ClosedAccountDate = null,
                    JoinedDate = System.DateTime.Now
                };

                userProfile.UserId = SqlMapperExtensions.Insert(sqlCon, userProfileEntity); // Call the Dapper Extension method to insert the new record
                userProfile.Firstname = userRegister.Firstname;
                userProfile.Username = userProfile.Username;
                userProfile.EmailAddress = userProfile.EmailAddress;

                Registration.SendWelcomeEmail(userRegister.EmailAddress, userRegister.Firstname); // Send welcome email to new user.
            }
        }

此行调用Dapper Extension Class

userProfile.UserId = SqlMapperExtensions.Insert(sqlCon, userProfileEntity); // Call the Dapper Extension method to insert the new record

调用以下内容,我在这里得到错误

当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery要求命令具有事务。该命令的Transaction属性尚未初始化

public static long Insert<T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null) where T : class
    {
        using (var tx = connection.BeginTransaction())
        {
            var type = typeof(T);

            var name = GetTableName(type);

            var sb = new StringBuilder(null);
            sb.AppendFormat("insert into {0} (", name);

            var allProperties = TypePropertiesCache(type);
            var keyProperties = KeyPropertiesCache(type);

            for (var i = 0; i < allProperties.Count(); i++)
            {
                var property = allProperties.ElementAt(i);
                if (keyProperties.Contains(property)) continue;

                sb.Append(property.Name);
                if (i < allProperties.Count() - 1)
                    sb.Append(", ");
            }
            sb.Append(") values (");
            for (var i = 0; i < allProperties.Count(); i++)
            {
                var property = allProperties.ElementAt(i);
                if (keyProperties.Contains(property)) continue;

                sb.AppendFormat("@{0}", property.Name);
                if (i < allProperties.Count() - 1)
                    sb.Append(", ");
            }
            sb.Append(") ");
// here is where the error occures vvvvvvvv
            connection.Execute(sb.ToString(), entityToInsert, transaction: transaction, commandTimeout: commandTimeout);
            //NOTE: would prefer to use IDENT_CURRENT('tablename') or IDENT_SCOPE but these are not available on SQLCE
            var r = connection.Query("select @@IDENTITY id");
            tx.Commit();
            return (int)r.First().id;
        }
    }

问题是我如何解决这个问题,我已经谷歌搜索并尝试了解决方案但无济于事。

由于

0 个答案:

没有答案