1

I have an ASP.NET web application using Entity Framework and a MySQL database. I am doing some work with dynamic tables so have resorted to writing raw SQL. Is there something I need to add to make this code thread-safe? This code can and will be called very frequently for every user of my system. It always the call against INFORMATION_SCHEMA that errors.

Here is the error I receive fairly often attempting to call AddMessageAction (but not everytime):

UserActionModel:CheckTableExists ex: The underlying provider failed on Open..
4/23/2013 9:00:24 AM: UserActionModel:CheckTableExists inner ex: System.NotSupportedException: Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.
   at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
   at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
   at MySql.Data.MySqlClient.MySqlConnection.Open()
   at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure).

And the code:

public static class UserActionModel
{

private const string databaseName = "chat";

public static string CheckTableExists(long _userId)
{
    string tableName = null;
    List<long> tableExists;

    try
    {
        string date = DateTime.Now.ToUniversalTime().Year.ToString() + DateTime.Now.ToUniversalTime().Month.ToString("D2") + DateTime.Now.ToUniversalTime().Day.ToString("D2");

        tableName = "user_actions_" + date + "_" + _userId;

        string sql = "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_NAME = '" + tableName + "' AND TABLE_SCHEMA = 'archive'";

        using (var readContext = new ArchiveConnector())
        {
            tableExists = readContext.Database.SqlQuery<long>(sql).ToList();
            readContext.Database.Connection.Close();
        }

        if (tableExists.Any(tableExist => tableExist == 0))
        {
            sql = "CREATE TABLE IF NOT EXISTS `" + tableName + "` ("
                  + "`id` bigint(20) NOT NULL AUTO_INCREMENT, "
                  + "`user_id` bigint(20) NOT NULL, "
                  + "`user_device_id` bigint(20) NOT NULL, "
                  + "`coordinate_address_id` bigint(20) NOT NULL, "
                  + "`message_id` bigint(20) DEFAULT NULL, "
                  + "`created` datetime NOT NULL, "
                  + "PRIMARY KEY (`id`), "
                  + "KEY `user_id` (`user_id`), "
                  + "KEY `user_device_id` (`user_device_id`), "
                  + "KEY `coordinate_address_id` (`coordinate_address_id`), "
                  + "KEY `message_id` (`message_id`); "

            using (var writeContext = new ArchiveConnector())
            {
                writeContext.Database.ExecuteSqlCommand(sql);
                writeContext.SaveChanges();
                writeContext.Database.Connection.Close();

            }
        }
    }
    catch (Exception ex)
    {
        Logger.LogMessage("UserActionModel:CheckTableExists ex: " + ex.Message);

        if (ex.InnerException != null)
            Logger.LogMessage("UserActionModel:CheckTableExists inner ex: " + ex.InnerException);

        tableName = null;
    }

    return tableName;
}

public static void AddMessageAction(long _messageId, long _userId, long _userDeviceId, long _coordinateAddressId)
{
    try
    {
        string tableName = CheckTableExists(_userId);

        if (String.IsNullOrEmpty(tableName)) return;

        using (var dataContext = new ArchiveConnector())
        {
            string sql = "INSERT INTO " + tableName + " "
                + "(user_id, user_device_id, coordinate_address_id, message_id, created) "
                + "VALUES "
                + "(" + _userId + ", " + _userDeviceId + ", " + _coordinateAddressId + ", " + _messageId + ", NOW());";

            dataContext.Database.ExecuteSqlCommand(sql);
            dataContext.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        Logger.LogMessage("UserActionModel:AddMessageAction (" + _messageId + ") ex: " + ex.Message);
    }
}
}    

Removing persist security info=True from my web.config connection string made no difference (I read about that being a possible solution).

UDPATE: updated from connector 6.6.4 to 6.6.5. no change. UDPATE: updated from connector 6.6.5 to 6.7.1 Alpha. no change.

4

2 に答える 2

0

ArchiveConnectorDisposeメソッドは MySQL 接続を閉じていません。次の場合:

using (var writeContext = new ArchiveConnector())

接続:

using (var readContext = new ArchiveConnector())

はまだ開いており、MySQL は同じトランザクションでの複数の接続をサポートしていません。で接続が閉じられていることを確認してくださいArchiveConnector.Dispose()

幸運を。

于 2013-04-23T14:47:31.813 に答える
0

私は別のコネクタのAddMessageAction()内から自分を呼び出していました。usingこんなことしないで。

于 2013-04-23T17:19:18.937 に答える