由于在内存中设置数据库非常容易,因此我一直在阅读使用Effort进行单元测试。我一直在尝试在我的测试数据服务中实现这一点,但是我一直遇到问题。
我正在使用Entity Framework 6和从现有表生成的模型。

上下文模型

public partial class Entities : DbContext
{
    public Entities()
        : base("name=Entities")
    {
    }

    //Overloading for effort unit test
    public Entities(DbConnection connection) : base(connection,true)
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<REPAIR_CHECK_IN_TABLE> REPAIR_CHECK_IN_TABLEs { get; set; }
    public virtual DbSet<tblPlanarWarranty> tblPlanarWarranties { get; set; }
}


测试数据服务

private IDataLoader loader;
    private Entities context;


    public TestDataService()
    {

        loader = new Effort.DataLoaders.CsvDataLoader(@"_TestDataFiles\");
        context = new Entities(Effort.DbConnectionFactory.CreateTransient(loader));
    }


最初,我会收到以下错误。


  不变名称为'Effort.Provider'的ADO.NET提供程序没有实体框架提供程序


然后,我将所述提供程序添加到应用程序配置文件的提供程序部分,并开始收到此错误。


  实体框架提供程序类型'Effort.ProviderServices,Effort,Version-1.0.0.0的'Instance'成员未返回继承自'System.Data.Entity.Core.Common.DBProviderServices'的对象


有人对我做错了什么有见识吗?在网站上,这很容易,只有几行,但这变成了一个巨大的混乱。

最佳答案

小心!使用EF6时,请勿安装ZZZ Projects的Effort!

通过相同的ZZZ项目安装Effort.EF6

class SchoolDbContext : DbContext
{
    // the standard constructors you probably already use:
    public SchooldDbContext() : base(...) {}
    public SchoolDbContext(string nameOrConnectionString) : base(nameOrConnectionString) {}

    // add this one for effort:
    public SchoolDbContext(DbConnection existingConnection, bool contextOwnsConnection)
        : base(existingConnection, contextOwnsConnection) { }

    ... // DbSets, etc


使用干净的空数据库

var dbConnection = Effort.DbConnectionFactory.CreateTransient();
using (var dbContext = new SchoolDbContext(dbConnection, true)
{
      dbContext.Schools.Add(new School {...});
      dbConext.SaveChanges();

      // this database exists as long as the connection exists
      var schoolCount = dbContext.Schools.Count();
      // expect one school
}

// a new empty database will be created: there won't be any schools
dbConnection = Effort.DbConnectionFactory.CreateTransient();
using (var dbContext = new SchoolDbContext(dbConnection)
{
     var schoolCount = dbContext.Schools.Count();
     // expect no schools
}


重用数据库

该数据库将在您的程序执行期间保持不变。该模型将仅蠕动一次。

const string dbName = "MyDb"
var dbConnection = Effort.DbConnectionFactory.CreatePersistent(dbName);
using (var dbContext = new SchoolDbContext(dbConnection)
{
      dbContext.Schools.Add(new School {...});
      dbContext.SaveChanges();
}

dbConnection = Effort.DbConnectionFactory.CreatePersistent(dbName);
using (var dbContext = new SchoolDbContext(dbConnection)
{
     var schoolCount = dbContext.Schools.Count();
     // expect the school you just added
}

关于c# - 测试时的工作量问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38441528/

10-09 05:38