使用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],主要講了include
和Load
的區別,前者會使用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