情况
我想启用我的 DbContext
的单元测试基于 Entity Framework 6。我使用数据库优先方法创建了我的 DbContext
和我的模型,现在有一个 .edmx 设计器文件。
问题
我自动创建的 DbContext
确实覆盖了 DbContext.OnModelCreating
像这样的方法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
我正在尝试根据 this article 的信息在我的模拟数据访问服务中创建我的 DbContext
的新实例.我的代码没有像这篇博文的作者指出的那样遇到 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'
在 stackoverflow 上有很多问题都集中在使用数据库优先方法时努力进行单元测试,但似乎没有人像我一样遇到类似的问题。
我已经尝试过的事情
- 长时间在互联网上搜索解决方案。
- 取消对覆盖的
OnModelCreating()
的注释。 - 我已经尝试申请this solution没有成功。
- 用 Moq 模拟我的
DbContext
,这绝对不是一个选择。
问题
我如何创建和使用内存数据库(努力)?
附加信息
当我取消注释 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);
}
关于c# - 无意代码第一异常 |使用数据库优先的 Effort.Ef6 Entity Framework 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46172095/