透過EF直接查詢現有的資料庫,而非走完整的Code First流程(Add Migration, update database…),故資料庫內不存在Table [__MigrationHistory],但執行查詢時記錄到的Log卻會發現EF會嘗試的查詢它並發生錯誤...
Google 了下找到了這篇文章
Using EF “Code First” with an Existing Database
在 Comments 中有提到 EF 實體建立後會與資料庫內的 [__MigrationHistory] 比較內容,而因為Table不存在,所以查詢會發生錯誤
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[__MigrationHistory] AS [Extent1]
WHERE [Extent1].[ContextKey] = @p__linq__0
) AS [GroupBy1]
-- p__linq__0: 'TestDbContext' (Type = String, Size = 4000)
-- Executing at 20/12/11 15:38:21 +08:00
-- Failed in 29 ms with error: Invalid object name 'dbo.__MigrationHistory'.
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[__MigrationHistory] AS [Extent1]
) AS [GroupBy1]
-- Executing at 20/12/11 15:38:21 +08:00
-- Failed in 1 ms with error: Invalid object name 'dbo.__MigrationHistory'.
可以修改對應的 DbContext 來關閉資料庫的初始化來處理這個錯誤
public TestDbContext()
: base("TestConnection")
{
Database.SetInitializer<TestDbContext>(null);
}