pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何將 TransactionScope 與 MySql 和實體框架一起使用

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

問題描述

我有一個新的 .NET 4.0 控制臺應用程序,它使用:

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

  • MySql 6.4.4.0
  • 實體框架 4.2(代碼優先)
  • Visual Studio 2010

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

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

現在,當我添加 TransactionScope 時,如下例所示:

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

當我運行這個時,我收到錯誤:

When I run this, I get the error:

當前不支持多個同時連接或在同一事務內具有不同連接字符串的連接.

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

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?

完整的錯誤信息

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: 

一些類(不復雜):

[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>

提前致謝,

推薦答案

試試這個,創建上下文后創建事務.

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

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

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

相關文檔推薦

SQL Server 2005 Transaction Level and Stored Procedures(SQL Server 2005 事務級和存儲過程)
Should I call Parameters.Clear when reusing a SqlCommand with a transation?(重用帶有事務的 SqlCommand 時,我應該調用 Parameters.Clear 嗎?)
Does SqlTransaction need to have Dispose called?(SqlTransaction 是否需要調用 Dispose?)
Reason for System.Transactions.TransactionInDoubtException(System.Transactions.TransactionInDoubtException 的原因)
Why doesn#39;t TransactionScope work with Entity Framework?(為什么 TransactionScope 不適用于實體框架?)
How to dispose TransactionScope in cancelable async/await?(如何在可取消的 async/await 中處理 TransactionScope?)
主站蜘蛛池模板: 糖衣机,除尘式糖衣机,全自动糖衣机,泰州市长江制药机械有限公司 体感VRAR全息沉浸式3D投影多媒体展厅展会游戏互动-万展互动 | 泰国专线_泰国物流专线_广州到泰国物流公司-泰廊曼国际 | 胜为光纤光缆_光纤跳线_单模尾纤_光纤收发器_ODF光纤配线架厂家直销_北京睿创胜为科技有限公司 - 北京睿创胜为科技有限公司 | 知名电动蝶阀,电动球阀,气动蝶阀,气动球阀生产厂家|价格透明-【固菲阀门官网】 | 洛阳防爆合格证办理-洛阳防爆认证机构-洛阳申请国家防爆合格证-洛阳本安防爆认证代办-洛阳沪南抚防爆电气技术服务有限公司 | 范秘书_懂你的范文小秘书 | 成都顶呱呱信息技术有限公司-贷款_个人贷款_银行贷款在线申请 - 成都贷款公司 | 温州中研白癜风专科_温州治疗白癜风_温州治疗白癜风医院哪家好_温州哪里治疗白癜风 | 南京展台搭建-南京展会设计-南京展览设计公司-南京展厅展示设计-南京汇雅展览工程有限公司 | 步进_伺服_行星减速机,微型直流电机,大功率直流电机-淄博冠意传动机械 | 临时厕所租赁_玻璃钢厕所租赁_蹲式|坐式厕所出租-北京慧海通 | 一体式钢筋扫描仪-楼板测厚仪-裂缝检测仪-泰仕特(北京) | 海水晶,海水素,海水晶价格-潍坊滨海经济开发区强隆海水晶厂 | 拉力机-拉力试验机-万能试验机-电子拉力机-拉伸试验机-剥离强度试验机-苏州皖仪实验仪器有限公司 | 舞台木地板厂家_体育运动木地板_室内篮球馆木地板_实木运动地板厂家_欧氏篮球地板推荐 | 别墅图纸超市|别墅设计图纸|农村房屋设计图|农村自建房|别墅设计图纸及效果图大全 | 光照全温振荡器(智能型)-恒隆仪器 | 杜甫仪器官网|实验室平行反应器|升降水浴锅|台式低温循环泵 | 儿童乐园|游乐场|淘气堡招商加盟|室内儿童游乐园配套设备|生产厂家|开心哈乐儿童乐园 | 网架支座@球铰支座@钢结构支座@成品支座厂家@万向滑动支座_桥兴工程橡胶有限公司 | 工业胀紧套_万向节联轴器_链条-规格齐全-型号选购-非标订做-厂家批发价格-上海乙谛精密机械有限公司 | 一体化净水器_一体化净水设备_一体化水处理设备-江苏旭浩鑫环保科技有限公司 | 集装袋吨袋生产厂家-噸袋廠傢-塑料编织袋-纸塑复合袋-二手吨袋-太空袋-曹县建烨包装 | 北京开业庆典策划-年会活动策划公司-舞龙舞狮团大鼓表演-北京盛乾龙狮鼓乐礼仪庆典策划公司 | 刮板输送机,粉尘加湿搅拌机,螺旋输送机,布袋除尘器 | 北京自然绿环境科技发展有限公司专业生产【洗车机_加油站洗车机-全自动洗车机】 | 3A别墅漆/3A环保漆_广东美涂士建材股份有限公司【官网】 | 2025福建平潭岛旅游攻略|蓝眼泪,景点,住宿攻略-趣平潭网 | 德国EA可编程直流电源_电子负载,中国台湾固纬直流电源_交流电源-苏州展文电子科技有限公司 | 油漆辅料厂家_阴阳脚线_艺术漆厂家_内外墙涂料施工_乳胶漆专用防霉腻子粉_轻质粉刷石膏-魔法涂涂 | 上海logo设计 | 广东燎了网络科技有限公司官网-网站建设-珠海网络推广-高端营销型外贸网站建设-珠海专业h5建站公司「了了网」 | 黑龙江「京科脑康」医院-哈尔滨失眠医院_哈尔滨治疗抑郁症医院_哈尔滨精神心理医院 | 昆明化妆培训-纹绣美甲-美容美牙培训-昆明博澜培训学校 | 蔡司三坐标-影像测量机-3D扫描仪-蔡司显微镜-扫描电镜-工业CT-ZEISS授权代理商三本工业测量 | Dataforth隔离信号调理模块-信号放大模块-加速度振动传感器-北京康泰电子有限公司 | 快速门厂家批发_PVC快速卷帘门_高速门_高速卷帘门-广州万盛门业 快干水泥|桥梁伸缩缝止水胶|伸缩缝装置生产厂家-广东广航交通科技有限公司 | 自动气象站_农业气象站_超声波气象站_防爆气象站-山东万象环境科技有限公司 | 同学聚会纪念册制作_毕业相册制作-成都顺时针宣传画册设计公司 | 槽钢冲孔机,槽钢三面冲,带钢冲孔机-山东兴田阳光智能装备股份有限公司 | 百度爱采购运营研究社社群-店铺托管-爱采购代运营-良言多米网络公司 |