[廚餘回收] Entity Framework Core 錯誤:「...cannot be tracked because another instance...」的原因與解法

從應用程式日誌看到下面這個 Entity Framework Core(以下簡稱 EF Core)發出的例外錯誤:

The instance of entity type 'MyTable' cannot be tracked because another instance with the same key value for {'Key'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

它的意思是,相同主索引鍵的實體無法被追蹤,因為已經有另一個實體正在被追蹤,我們來看看怎麼回事。

...繼續閱讀 »

[小菜一碟] Entity Framework Core 如何在單一查詢中跨資料庫查詢資料?

如果資料庫都隸屬於同一台伺服器,資料庫之間要 JOIN 彼此的資料表是相對容易的,在有權限的前提下,只要在資料表的前面加上「[資料庫名稱].[結構描述]」,就能存取得到其他資料庫的資料表,就像這樣:[DB].[dbo].[Table]

但是在 Entity Framework Core 中,似乎沒有那麼容易,通常一個資料庫會建成一個 DbContext,當我們直接把隸屬於不同 DbContext 的 DbSet 拿來做 Join,我們得到以下的錯誤訊息:

Cannot use multiple context instances within a single query execution. Ensure the query uses a single context instance.

...繼續閱讀 »