久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何將 TransactionScope 與 MySql 和實(shí)體框架一起使用

How do I use TransactionScope with MySql and Entity Framework? (getting Multiple simultaneous connections...are not currently supported error)(如何將 TransactionScope 與 MySql 和實(shí)體框架一起使用?(獲取多個(gè)同時(shí)連接...目前不
本文介紹了如何將 TransactionScope 與 MySql 和實(shí)體框架一起使用?(獲取多個(gè)同時(shí)連接...目前不支持錯(cuò)誤)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!

問(wèn)題描述

我有一個(gè)新的 .NET 4.0 控制臺(tái)應(yīng)用程序,它使用:

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

  • MySql 6.4.4.0
  • 實(shí)體框架 4.2(代碼優(yōu)先)
  • Visual Studio 2010

到目前為止,這是有效的.我可以很好地添加和讀取數(shù)據(jù)庫(kù).

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

現(xiàn)在,當(dāng)我添加 TransactionScope 時(shí),如下例所示:

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);  <-- exception occurs here

            context.SaveChanges();
        }
    }
}

當(dāng)我運(yùn)行這個(gè)時(shí),我收到錯(cuò)誤:

When I run this, I get the error:

當(dāng)前不支持多個(gè)同時(shí)連接或在同一事務(wù)內(nèi)具有不同連接字符串的連接.

似乎即使是最新版本的 MySql 也不喜歡 TransactionScope 與 EntityFramework 一起工作.

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

我希望能夠使用事務(wù),尤其是在測(cè)試項(xiàng)目中,以便我可以回滾任何更改.

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

知道如何解決或解決此問(wèn)題嗎?

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

完整的錯(cuò)誤信息

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.<InitializeDatabase>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<T>.GetEnumerator()
        at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
        at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>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.<PerformDatabaseInitialization>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: 

一些類(不復(fù)雜):

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

App.config:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <clear/>
    <add name="DbContext" connectionString="Server=localhost; Database=****; Uid=****; Pwd=****;" providerName="MySql.Data.MySqlClient"/>
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient"/>
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data"/>
    </DbProviderFactories>
  </system.data>
</configuration>

提前致謝,

推薦答案

試試這個(gè),創(chuàng)建上下文后創(chuàng)建事務(wù).

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

這篇關(guān)于如何將 TransactionScope 與 MySql 和實(shí)體框架一起使用?(獲取多個(gè)同時(shí)連接...目前不支持錯(cuò)誤)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

SQL Server 2005 Transaction Level and Stored Procedures(SQL Server 2005 事務(wù)級(jí)和存儲(chǔ)過(guò)程)
Should I call Parameters.Clear when reusing a SqlCommand with a transation?(重用帶有事務(wù)的 SqlCommand 時(shí),我應(yīng)該調(diào)用 Parameters.Clear 嗎?)
Does SqlTransaction need to have Dispose called?(SqlTransaction 是否需要調(diào)用 Dispose?)
Reason for System.Transactions.TransactionInDoubtException(System.Transactions.TransactionInDoubtException 的原因)
Why doesn#39;t TransactionScope work with Entity Framework?(為什么 TransactionScope 不適用于實(shí)體框架?)
How to dispose TransactionScope in cancelable async/await?(如何在可取消的 async/await 中處理 TransactionScope?)
主站蜘蛛池模板: 一级免费看 | 国产性生活 | 欧美久久久 | 亚洲一区在线观看视频 | 久久99久久久 | 欧美一级大片 | 丰满少妇高潮无套内谢 | 久久久精品在线 | 亚洲色诱 | 伊人在线视频 | 欧美激情综合五月色丁香 | 国产福利视频在线观看 | 亚洲另类色图 | 精品视频在线观看 | 一区二区黄色 | 国产成人在线免费观看 | 亚洲精品无 | 黄色小视频在线观看 | 亚洲国产日本 | 欧美狠狠操 | 又黄又爽又刺激的视频 | 国产一区不卡 | 亚洲视频一区二区三区 | 福利片在线观看 | 国产精品999 | www.久草 | 综合激情网 | 黄色免费片| 一区二区在线免费观看 | 福利在线播放 | 好吊日在线视频 | 特一级黄色片 | 亚洲永久免费视频 | 久久久婷婷 | 99在线精品视频 | 成人免费网站黄 | 国产成人免费在线视频 | av噜噜噜| 可以免费看的av | 成人免费视频视频 | 久久久在线|