请参阅下面的代码.如果我初始化多个实体上下文,那么我只在第二组代码上得到以下异常.如果我注释掉第二组就行了.
{"底层提供商在Open上失败."}
内部:{"与基础事务管理器的通信失败."}
内部:{"错误HRESULT E_FAIL已从调用COM组件返回."}
请注意,这是一个示例应用程序,我知道连续创建2个上下文没有意义.但是,生产代码确实有理由在同一个环境中创建多个上下文TransactionScope,并且无法更改.
编辑
这是我之前尝试设置MS-DTC的问题.它似乎在服务器和客户端上都启用了.我不确定它是否设置正确.另请注意,我尝试这样做的原因之一是TransactionScope使用ADO.NET和Linq 2 Sql 中的现有代码...我希望那些也使用相同的事务.(这可能听起来很疯狂,但如果可能,我需要让它工作).
解
Windows防火墙阻止了与MS-DTC的连接.
using(TransactionScope ts = new System.Transactions.TransactionScope())
{
using (DatabaseEntityModel o = new DatabaseEntityModel())
{
var v = (from s in o.Advertiser select s).First();
v.AcceptableLength = 1;
o.SaveChanges();
}
//-> By commenting out this section, it works
using (DatabaseEntityModel o = new DatabaseEntityModel())
{
//Exception on this next line
var v = (from s1 in o.Advertiser select s1).First(); v.AcceptableLength = …Run Code Online (Sandbox Code Playgroud) 问题:(使用Sql 2005)
所以我发现了这么多:
[TestMethod]
public void CreateUser()
{
TransactionScope transactionScope = new TransactionScope();
DataContextHandler.Context.AddToForumUser(userToTest);
DataContextHandler.Context.SaveChanges();
DataContextHandler.Context.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
DataContextHandler只是一个简单的单例,它为我的实体公开了上下文对象.这似乎就像你想象的那样有效.它创建用户,保存,然后在程序结束时回滚.(IE测试结束)
问题:如何强制事务回滚并自行终止以便我可以查询表?
原因:出于测试目的,我想确保用户:
目前,如果测试结束,我只能让事务回滚,而我无法弄清楚如何查询事务:
[TestMethod]
public void CreateUser()
{
ForumUser userToTest = new ForumUser();
TransactionScope transactionScope = new TransactionScope();
DataContextHandler.Context.AddToForumUser(userToTest);
DataContextHandler.Context.SaveChanges();
Assert.IsTrue(userToTest.UserID > 0);
var foundUser = (from user in DataContextHandler.Context.ForumUser
where user.UserID == userToTest.UserID
select user).Count(); //KABOOM Can't query since the
//transaction has the table locked.
Assert.IsTrue(foundUser == 1);
DataContextHandler.Context.Dispose();
var after = (from user in …Run Code Online (Sandbox Code Playgroud) 以下是我的解决方案的概述:

这是我的PizzaSoftwareData类:
namespace PizzaSoftware.Data
{
public class PizzaSoftwareData : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<User> Users { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
根据Scott Guthrie博客上的一个示例,您必须在应用程序的开头运行此代码才能创建/更新数据库架构.
Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());
Run Code Online (Sandbox Code Playgroud)
我在PizzaSoftware.UI中运行Program.cs中的那行代码.
namespace PizzaSoftware.UI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());
Application.Run(new LoginForm());
}
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我为什么数据库没有创建表? …
我创建了一个Windows应用程序.当我手动执行我的可执行文件时,它工作正常,但是当我使用Windows服务运行我的exe时,它显示提供失败错误.我正在使用实体框架.实体框架有什么问题吗?
这是我的代码:
private void Threadfun()
{
try
{
System.Diagnostics.Process.Start(@"D:\V-Tec\bin\Debug\VibrantIndexerForm.exe");
if (System.IO.File.Exists(@"D:\VibrantIndexerSetup\MarcExport1.txt"))
{
}
else
{
System.IO.File.Create(@"D:\VibrantIndexerSetup\MarcExport1.txt").Dispose();
}
System.IO.File.WriteAllText(@"D:\VibrantIndexerSetup\MarcExport1.txt", System.DateTime.Now.ToString());
System.Threading.Thread.Sleep(100);
}
catch (Exception ex)
{
}
}
private void time_Elapsed(object sender, ElapsedEventArgs e)
{
m_thread = new System.Threading.Thread(new System.Threading.ThreadStart(Threadfun));
if (m_thread.IsAlive)
{
}
else
{
m_thread.Start();
}
}
protected override void OnStart(string[] args)
{
if (time.Enabled == false)
{
time.Elapsed += new ElapsedEventHandler(time_Elapsed);
time.Interval = 2000;
time.Enabled = true;
}
}
protected override void OnStop()
{
time.Enabled = false;
} …Run Code Online (Sandbox Code Playgroud) 我有一个带有.NET 4的Windows窗体应用程序和用于数据层的实体框架我需要一个带有事务的方法,但是进行简单的测试我无法使其工作
在BLL中:
public int Insert(List<Estrutura> lista)
{
using (TransactionScope scope = new TransactionScope())
{
id = this._dal.Insert(lista);
}
}
Run Code Online (Sandbox Code Playgroud)
在DAL:
public int Insert(List<Estrutura> lista)
{
using (Entities ctx = new Entities (ConnectionType.Custom))
{
ctx.AddToEstrutura(lista);
ctx.SaveChanges(); //<---exception is thrown here
}
}
Run Code Online (Sandbox Code Playgroud)
"底层提供商在Open上失败了."
有人有主意吗?
问题解决 - 我的解决方案
我解决了我的问题做了一些改变.在我的一个DAL中,我使用批量插入和其他实体.问题事务是由于事务的大部分(事务sql)不理解事务范围这一事实所以我在DAL中分离了实体并在运行中使用了sql事务.ExecuteScalar();
我相信这不是最优雅的方式,但解决了我的问题交易.
这是我的DAL的代码
using (SqlConnection sourceConnection = new SqlConnection(Utils.ConnectionString()))
{
sourceConnection.Open();
using (SqlTransaction transaction = sourceConnection.BeginTransaction())
{
StringBuilder query = new StringBuilder();
query.Append("INSERT INTO...");
SqlCommand command = new SqlCommand(query.ToString(), sourceConnection, transaction);
using (SqlBulkCopy …Run Code Online (Sandbox Code Playgroud) 我正在使用 asp.net web api,当我在内置服务器的 micro soft Visual Studio 上运行我的项目时,一切正常,但是当我将它托管在本地 iis 服务器上时,出现以下错误
底层提供者在 Open 上失败
我正在使用实体框架,我在 web.config 中的连接字符串是
<add name="Entities" connectionString="metadata=res://*/Models.School.csdl|res://*/Models.School.ssdl|res://*/Models.School.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=DBName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Run Code Online (Sandbox Code Playgroud)