.net mysql transactionscope,我如何使用的TransactionScope使用MySQL和实体框架? (越来越多的并发连接......目前不支持错误)...

I have a new .NET 4.0 console application that uses:

MySql 6.4.4.0

Entity Framework 4.2 (code-first)

Visual Studio 2010

So far this works. I can add and read from the database fine.

Now, when I add TransactionScope, as in the following example:

public static void TestInsert()

{

using (TransactionScope scope = new TransactionScope())

{

using (var context = new MyDbContext())

{

// Create a test user

DateTime dt = DateTime.Now;

var user1 = new User { UserID = 1, UserName = "test" };

context.Users.Add(user1);

context.SaveChanges();

}

}

}

When I run this, I get the error:

Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.

It seems that even the latest version of MySql does not like TransactionScope working with EntityFramework.

I want to be able to use transactions, especially in test projects so that I can roll back any changes.

Any idea how I can fix this or work around it?

Full error information

System.Data.DataException was unhandled

Message=An exception occurred while initializing the database. See the InnerException for details.

Source=EntityFramework

StackTrace:

at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)

at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()

at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)

at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)

at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)

at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()

at System.Data.Entity.Internal.InternalContext.Initialize()

at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)

at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()

at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()

at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)

at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)

at System.Data.Entity.DbSet`1.Add(TEntity entity)

InnerException: System.Data.EntityException

Message=The underlying provider failed on Open.

Source=System.Data.Entity

StackTrace:

at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)

at System.Data.EntityClient.EntityConnection.Open()

at System.Data.Objects.ObjectContext.EnsureConnection()

at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)

at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()

at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)

at System.Data.Objects.ELinq.ObjectQueryProvider.b__1[TResult](IEnumerable`1 sequence)

at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)

at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)

at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)

at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)

at System.Data.Entity.Internal.InternalContext.QueryForModelHash()

at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata)

at System.Data.Entity.Database.CompatibleWithModel(Boolean throwIfNoMetadata)

at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)

at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass5.b__3()

at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)

InnerException: System.NotSupportedException

Message=Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.

Source=MySql.Data

StackTrace:

at MySql.Data.MySqlClient.MySqlConnection.Open()

at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)

InnerException:

Some of the classes (nothing complicated):

[Table("User")]

public class User

{

public User()

{

}

// Primary key

[Key]

public int UserID { get; set; }

public string UserName { get; set; }

}

public class MyDbContext : DbContext

{

public MyDbContext() : base("DbContext")

{

}

public DbSet Users { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)

{

// Tell Code First to ignore PluralizingTableName convention

// If you keep this convention then the generated tables will have pluralized names.

modelBuilder.Conventions.Remove();

}

}

App.config:

Thanks in advance,

Dan

解决方案

Try this, Create transaction after creating context.

public static void TestInsert()

{

using (var context = new MyDbContext())

{

using (TransactionScope scope = new TransactionScope())

{

// Create a test user

DateTime dt = DateTime.Now;

var user1 = new User { UserID = 1, UserName = "test" };

context.Users.Add(user1);

context.SaveChanges();

scope.Complete();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Transactions.doTran是一个方法,它用于手动处理事务。这个方法包含了一些操作,并且在操作成功后调用了ContextUtil.SetComplete()来标记事务已完成,如果操作失败则调用了ContextUtil.SetAbort()来标记事务已中止。这个方法返回一个字符串,如果所有操作都成功执行,则返回"方法执行成功",否则返回"两个方法至少有一个执行失败!"。 另外,还有一种自动处理事务的方法,可以在方法上加上[AutoComplete(true)]特性,然后使用Using语句来创建一个TransactionScope对象,这样就可以自动处理事务。在Using语句块中执行具体的操作,如果操作成功,则事务会自动提交;如果操作失败,则事务会自动回滚。 总的来说,Transactions.doTran是一个用于手动处理事务的方法,而使用System.Transactions命名空间中的TransactionScope类可以实现自动处理事务。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [asp.net事务机制](https://blog.csdn.net/weixin_30284355/article/details/96262580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [数据库的事务和锁机制(SQL Server)](https://blog.csdn.net/oathevil/article/details/5617113)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值