linq2db (@github)支持Linq訪問多種數據庫。使用它操作MySQL非常簡單,但使用方式上有一些“新奇”,特記錄一下。
下載安裝(@NuGet)以及使用教程(@For MySQL)。
使用NuGet安裝之后,在工程目錄下會生成project\LinqToDB.Templates目錄。該目錄下列舉出了各種數據庫的使用辦法,其中MySQL內容如下:
<#@ template language="C#" debug="True" hostSpecific="True" #>
<#@ output extension=".generated.cs" #>
<#@ include file="$(ProjectDir)LinqToDB.Templates\LinqToDB.MySql.Tools.ttinclude" #>
<#@ include file="$(ProjectDir)LinqToDB.Templates\PluralizationService.ttinclude" #>
<#
/*
1. Copy this file to a folder where you would like to generate your data model,
rename it, and delete .txt extension. For example:
MyProject
DataModels
MyDatabase.tt
2. Modify the connection settings below to connect to your database.
3. Add connection string to the web/app.config file:
<connectionStrings>
<add name="MyDatabase" connectionString="Server=MyServer;Port=3306;Database=MyDatabase;Uid=root;Pwd=TestPassword;charset=utf8;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
4. To access your database use the following code:
using (var db = new MyDatabaseDB())
{
var q =
from c in db.Customers
select c;
foreach (var c in q)
Console.WriteLine(c.ContactName);
}
5. See more at https://github.com/linq2db/t4models/blob/master/Templates/ReadMe.LinqToDB.md.
*/
NamespaceName = "DataModels";
LoadMySqlMetadata("MyServer", "MyDatabase", "root", "TestPassword");
// LoadMySqlMetadata(string connectionString);
GenerateModel();
#>
按照文件的說明,具體操作如下:
- 將此文件拷貝到數據訪問命名空間下。比如Model\
- 改名。改為SpData.tt,主要是后綴名。
- 修改連接串。主要是“LoadMySqlMetadata("MyServer", "MyDatabase", "root", "TestPassword");” 改為自己用的鏈接信息,分為是Mysql Server Ip,目標數據,用戶名和密碼。
- 將連接串模板修改后,添加到web.config或者app.config。例如web.config 加入到 <configuration>下即可。
- SpData.tt會SpDatabase.generated.cs。如果MySQL信息正確,則會看到生成的數據庫、表格等“OR”類。
- 示例需要改動的地方:將命名空間改為實際的或自定義的命名空間;將new MyDatabaseDB()改為SpDatabase.generated.cs中第一個類(即數據庫)生成的數據庫名類,見下圖。
手動運行:
運行之后生成文件: