TransactionScope和SQLite数据库被锁定
发布时间:2020-12-12 23:43:49 所属栏目:百科 来源:网络整理
导读:我试图使用Entite Framework 6与SQLite,并在尝试使用TransactionScope时遇到数据库锁定问题.这是我的代码: using (var txn = new TransactionScope()){ using (var ctx = new CalibreContext()) { var book = ctx.Books.First(x = x.Id == 2); var author =
我试图使用Entite Framework 6与SQLite,并在尝试使用TransactionScope时遇到数据库锁定问题.这是我的代码:
using (var txn = new TransactionScope()) { using (var ctx = new CalibreContext()) { var book = ctx.Books.First(x => x.Id == 2); var author = ctx.Authors.First(x => x.Id == 3); book.Authors.Add(author); ctx.SaveChanges(); } txn.Complete(); } 第一行var book = ctx.Books.First(x => x.Id == 2);执行正常.但是一旦我继续下一个,我得到一个例外,说我的数据库被锁定了.这是我的应用配置: <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,EntityFramework,Version=6.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!-- For more information on Entity Framework configuration,visit http://go.microsoft.com/fwlink/?LinkID=237468 --> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /> </startup> <connectionStrings> <add name="CalibreContext" connectionString="Data Source=metadata.db" providerName="System.Data.SQLite.EF6" /> </connectionStrings> <system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite" /> <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory,System.Data.SQLite,Version=1.0.98.0,PublicKeyToken=db937bc2d44ff139" /> <remove invariant="System.Data.SQLite.EF6" /> <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".Net Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory,System.Data.SQLite.EF6,PublicKeyToken=db937bc2d44ff139" /> </DbProviderFactories> </system.data> <entityFramework> <defaultConnectionFactory type="Calibre.Dal.Ef.SQLiteConnectionFactory,Calibre.Dal.Ef" /> <providers> <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices,PublicKeyToken=db937bc2d44ff139" /> <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices,PublicKeyToken=db937bc2d44ff139" /> </providers> </entityFramework> </configuration> 我需要使用TransactionScope,因为除了执行数据库操作之外,我还必须执行我计划添加到同一事务(目前不存在)的文件系统操作. 我遇到了类似的问题.为了清楚起见,我在第二个查询中得到的错误是“底层提供程序在Open上失败”(但Open失败的原因是数据库被锁定).显然这个问题与MSDTC有关(TransactionScope与MSDTC紧密耦合). 我找到了a community addition to an MSDN page,后者又引用了this blog post 解决方案是显式打开数据库连接: using (var txn = new TransactionScope()) { using (var ctx = new CalibreContext()) { ctx.Connection.Open(); // ... remainder as before ... 或者,如果所有CalibreContext对象都是短暂的,您可以想象在CalibreContext构造函数中打开连接. 这似乎解决了我的问题.如果我还有其他要报告的内容,我会发布更新. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |