MySQL with Entity Framework

使用Database First方式

需要安裝mysql-for-visualstudio-1.2.7.msi,以及mysql-connector-net-6.9.9.msi。

在VS2013中執行如下步驟:

  • 添加ADO.NET實體數據模型,下一步
  • 選擇“來自數據庫的Code First”,下一步
  • 使用數據提供程序“.Net Framework Data Provider for MySQL”建立數據連接
  • 完成后選擇需要映射成實體類的數據庫表。

使用Load()和Local

性能考量

參考資料[1],主要講了includeLoad的區別,前者會使用Join生成復雜的SQL語句,后者則是簡單的Select語句。對于遠程SQL訪問大數據,前者可能對于性能很有好處。

As a quick rule-of-thumb, I try to avoid having any more than three Include calls in a single query. I find that EF's queries get to ugly to recognize beyond that; it also matches my rule-of-thumb for SQL Server queries, that up to four JOIN statements in a single query works very well, but after that it's time to consider refactoring.

問題集

MySQL的設置問題

Entity Framework連接MySQL時,出現如下錯誤:

'System.Data.StrongTypingException: The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull . ---> System.InvalidCastException: Specified cast is not valid.
由于出現以下異常,無法生成模型:“表“TableDetails”中列“IsPrimaryKey”的值為DBNull.

Entity Framework (version 6.1.3) and MySQL Server (>= 5.7.6)

One way to resolve the issue is,

1. Open Services (services.msc) and restart MySQL57 service.
2. Execute the following commands in MySQL.
   use <<database name>>;
   set global optimizer_switch='derived_merge=OFF';

這樣就可以解決問題了。
其中derived_merge的含義是“Controls merging of derived tables and views into outer query block”,默認情況下是打開的。

The derived_merge flag controls whether the optimizer attempts to merge derived tables and view references into the outer query block, assuming that no other rule prevents merging; for example, an ALGORITHM directive for a view takes precedence over the derived_merge setting. By default, the flag is on to enable merging. For more information, see Section 8.2.2.3, “Optimizing Derived Tables and View References”.

參考

[1] c# - .Include() vs .Load() performance in EntityFramework

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 渣了一年的游戲了,遇到的噴子也是不計其數。 然后就得出一個結論,你得進去就屏蔽隊友,不然,在國服,這游...
    萌軟傲嬌妹閱讀 487評論 0 0
  • 我最大的感受就是我很幸運,還好沒錯過或者破壞孩子的興趣愛好。我也很痛恨自己,為什么沒早點看完這本書,孩子出生前就已...
    夢遠路近閱讀 345評論 0 1
  • 愛情和親情只是人生中的兩個重要組成部分,把愛情親情當成一生的人沒法體驗到人生更多的可能,我認為要充分地利用完短暫的...
    0818ba15cc2b閱讀 226評論 0 1
  • 在青山綠水之間,我想牽著你的手,走過這座橋,橋上是綠葉紅花,橋下是流水人家,橋的那頭是青絲,橋的這頭是白發。 我看...
    李青_青青巴學園閱讀 397評論 0 0