无意代码第一异常 | Entity Framework 使用数据库优先的 Effort.Ef6 单元测试

UnintentionalCodeFirstException | Entity Framework Unit Testing with Effort.Ef6 using Database First

情况

我想启用基于 entity framework 的 DbContext 单元测试 6. 我已经使用数据库优先方法创建了 DbContext 和我的模型,现在有一个 .edmx 设计器文件.

问题

我自动创建的 DbContext 确实覆盖了 DbContext.OnModelCreating 方法,如下所示:

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

我正在尝试根据 this article 的信息在我的模拟数据访问服务中创建我的 DbContext 的新实例。我的代码不会像本博客 post 的作者指出的那样 运行 变成 Database.SetInitializer;。我的构造函数看起来和他的一模一样。我的 DbContext 初始化如下所示:

public DatabaseEntities(DbConnection connection) 
     : base(connection, true) { }

当达到前面提到的覆盖 OnModelCreating

时会导致以下异常

System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: 'The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715'

Whosebug 上有很多问题都集中在使用数据库优先方法时努力进行单元测试,但似乎没有人有像我这样的问题。

我已经尝试过的事情

问题

我如何创建和使用内存数据库(努力)?


附加信息

当我取消注释 OnModelCreating() 时,将在第一次访问 DataContext 时抛出异常。例如:

DbConnection effortConnection = Effort.DbConnectionFactory.CreatePersistent("MockedDatabaseEntities");

using (DatabaseEntities dataContext = new DatabaseEntities(effortConnection))
{
    dataContext.Students.Count(); // Exception throws here
}

System.Data.Entity.ModelConfiguration.ModelValidationException: 'One or more validation errors were detected during model generation: MyApplication.Shared.Model.KeyValuePair: : EntityType 'KeyValuePair' has no key defined. Define the key for this EntityType. KeyValuePairs: EntityType: EntitySet 'KeyValuePairs' is based on type 'KeyValuePair' that has no keys defined.'

问题是我必须为我的 KeyValuePair 数据集指定键。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<KeyValuePair>().HasKey(x => x.Key);
    base.OnModelCreating(modelBuilder, null);
}

非常感谢 Robert Jørgensgaard Engdahl !

如果有人正在寻找 db-first 方法的解决方案,这对我有用:

string connStr = @"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;";
DbConnection connection = EntityConnectionFactory.CreateTransient(connStr);
return new MyDatabaseContext(connection);

我从 web/app.config.
中得到了 connStr 部分 另外,我没有碰 OnModelCreating.