测试初始化​​中的 EntityFramework 错误:多语句事务中不允许 CREATE DATABASE 语句

2024-02-07

我正在尝试构建一个快速测试,每次运行时都会删除并重新创建数据库。我有以下内容:

[TestClass]
public class PocoTest
{
    private TransactionScope _transactionScope;
    private ProjectDataSource _dataSource; 
    private Repository _repository = new Repository();
    private const string _cstring = "Data Source=.;Initial Catalog=test_db;Trusted_Connection=True";

    [TestInitialize]
    public virtual void TestInitialize()
    {
        _dataSource = new ProjectDataSource(_cstring);
        _dataSource.Database.Delete();
        _dataSource.Database.CreateIfNotExists();
        _transactionScope = new TransactionScope();
    }
    [TestMethod]
    public void TestBasicOperations()
    {                
        var item = _repository.AddItem(new Item(){Details = "Test Item"});
        //  AddItem makes a call through the data context to add a set and then calls datacontext.SaveChanges()
    }


    [TestCleanup]
    public void TestCleanup()
    {
        // rollback
        if (_transactionScope != null)
        {
            _transactionScope.Dispose();
        }
    }

但是,当我运行测试时,出现以下错误:

结果消息:测试方法 Project.Repository.UnitTests.PocoTest.TestBasicOperations 抛出 异常:System.Data.SqlClient.SqlException:创建数据库 多语句事务中不允许使用语句。

项目数据源在这里:

public class ProjectDataSource : DbContext, IProjectDataSource
{

    public ProjectDataSource() : base("DefaultConnection")
    {

    }

    public ProjectDataSource(string connectionString) : base(connectionString)
    {

    }

    public DbSet<Set> Sets { get; set; }
}

存储库:

public class Repository : IRepository
{
    private readonly ProjectDataSource _db = new ProjectDataSource();
    public Item AddItem(Item item)
        {
            _db.Items.Add(item);
            _db.SaveChanges();
            return item;
        }
}

为什么会发生这种情况?

另外 - 如果有任何区别 - 如果我注释掉 TestMethod 中的 AddItem 行,则不会发生错误。


您还可以使用db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sqlCommand);

See https://stackoverflow.com/a/24344654/375114 https://stackoverflow.com/a/24344654/375114欲了解详情

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

测试初始化​​中的 EntityFramework 错误:多语句事务中不允许 CREATE DATABASE 语句 的相关文章

随机推荐