[英]UnintentionalCodeFirstException | Entity Framework Unit Testing with Effort.Ef6 using Database First
我想基於實體框架 6 啟用我的DbContext
的單元測試。我已經使用數據庫優先方法創建了我的DbContext
和我的模型,現在有一個.edmx設計器文件。
我自動創建的DbContext
確實像這樣覆蓋了DbContext.OnModelCreating
方法:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
我正在嘗試根據本文的信息在我的DbContext
數據訪問服務中創建我的DbContext
的新實例。 我的代碼沒有運行到Database.SetInitializer;
就像這篇博文的作者指出的那樣。 我的構造函數看起來和他的一模一樣。 我的DbContext
初始化如下所示:
public DatabaseEntities(DbConnection connection)
: base(connection, true) { }
當到達前面提到的重寫的OnModelCreating
時會導致以下異常
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: '上下文正在代碼優先模式下使用,代碼是從數據庫優先或模型優先開發的 EDMX 文件生成的。 這將無法正常工作。 要解決此問題,請不要刪除引發此異常的代碼行。 如果您希望使用 Database First 或 Model First,請確保實體框架連接字符串包含在啟動項目的 app.config 或 web.config 中。 如果您要創建自己的 DbConnection,請確保它是 EntityConnection 而不是某種其他類型的 DbConnection,並將其傳遞給采用 DbConnection 的基本 DbContext 構造函數之一。 要了解有關代碼優先、數據庫優先和模型優先的更多信息,請參閱此處的實體框架文檔: http : //go.microsoft.com/fwlink/?LinkId=394715 '
有很多關於 stackoverflow 的問題都集中在使用數據庫優先方法時努力進行單元測試,但似乎沒有人像我一樣有類似的問題。
我如何創建和使用內存數據庫(努力)?
附加信息
當我取消對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: '在模型生成過程中檢測到一個或多個驗證錯誤:MyApplication.Shared.Model.KeyValuePair:: EntityType 'KeyValuePair' 沒有定義鍵。 定義此 EntityType 的鍵。 KeyValuePairs: EntityType: EntitySet 'KeyValuePairs' 基於未定義鍵的類型 'KeyValuePair'。
如果有人正在尋找 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
。
問題是我必須為我的 KeyValuePair 數據集指定鍵。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<KeyValuePair>().HasKey(x => x.Key);
base.OnModelCreating(modelBuilder, null);
}
非常感謝羅伯特·約根斯加德·恩達爾!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.