在VS2010中應用Entity framework與MySQL
羅朝輝 (http://www.cnblogs.com/kesalin/)
本文講述了在VS2010中使用EF與MySQL的一個簡單示例。
工具安裝:
1,MySQL
分別下載上面的三個軟件,注意:VS2010目前支持的最好的是 Connector/NET 6.3.5,下載其他版本可能需要進一步的修改配置,最好安裝此版本。然后依次安裝,注意修改MySQL的初始密碼並記住。
2,確認安裝了 ADO.NET Entity Data Model
右擊已有的C#工程,然后選擇 Add New Item,在 Visual C# Items->Data欄目中看看有沒有ADO.NET Entity Data Model選項,如果沒有則還沒有安裝該模板;或你也可以在VS安裝目錄下看看C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Data\1033\AdoNetEntityDataModelCSharp.zip 該文件存在不存在,如果不存在則需要安裝該模板。如何安裝呢,插入VS安裝盤,選擇修復,選中該組件安裝就可以了。
3,使用MySQL workbench在 MySQL表中新建數據庫 EFSample,在其中新建表customer,該表包含三個字段 id, Address, Name。如下所示:
4,新建C#控制台程序 EFSample,然后右擊工程名,然后選擇 Add New Item,在 Visual C# Items->Data中選擇ADO.NET Entity Data Model,命名為 EFSampleModel.edmx:
然后選擇從數據庫生成:
然后設置New Connection,選擇MySQL Provider,如下所示:
選擇要映射的數據庫與表,並將模型命名為EFSampleModel:
至此,我們就能夠在工程中看到創建的EFSampleModel.edmx:
5,我們可以使用xml編輯打開 EFSampleModel.edmx,在這個文件中定義了SSDL content,CSDL content以及 C-S mapping content。同樣,EF為我們自動生成了與數據庫對於的運行時類,這些類被定義在EFSampleModel.Designer.cs文件中,其中有對customer類的定義。該類定義了一個工程方法,我們可以使用該工廠方法來生成 customer 對象。
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="EFSampleModel", Name="customer")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class customer : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new customer object.
/// </summary>
/// <param name="address">Initial value of the Address property.</param>
/// <param name="id">Initial value of the id property.</param>
/// <param name="name">Initial value of the Name property.</param>
public static customer Createcustomer(global::System.String address, global::System.Int64 id, global::System.String name)
{
customer customer = new customer();
customer.Address = address;
customer.id = id;
customer.Name = name;
return customer;
}
#endregion
}
6,新建 customer的部分類來添加對象的描述:
namespace EFSample
{
public partial class customer : global::System.Data.Objects.DataClasses.EntityObject
{
override public string ToString()
{
return string.Format("Customer Name: {0}, Address: {1}", this.Name, this.Address);
}
}
}
7,支持大部分配置工作完成,下面開始編寫與數據庫進行交互相關的代碼。修改 Program.cs為:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace EFSample
{
class Program
{
const int MaxRow = 10;
static void DeleteData()
{
using (var ctx = new EFSampleEntities())
{
var customers = from c in ctx.customer select c;
foreach (customer c in customers)
{
ctx.DeleteObject(c);
}
ctx.SaveChanges();
}
}
static void InsertData(customer[] cs)
{
using (var ctx = new EFSampleEntities())
{
foreach (customer c in cs)
{
ctx.AddTocustomer(c);
}
ctx.SaveChanges();
}
}
static void QueryData()
{
using (var ctx = new EFSampleEntities())
{
for (int i = 1; i <= MaxRow; i++)
{
String str = i.ToString();
var results = ctx.customer.Where(c => c.Address == str);
foreach (customer c in results)
{
Console.WriteLine(c);
}
}
}
}
static void Main(string[] args)
{
customer[] cs = new customer[MaxRow];
for (int i = 1; i <= MaxRow; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append("用戶");
sb.Append(i);
customer c = customer.Createcustomer(i.ToString(), i, sb.ToString());
cs[i - 1] = c;
}
Console.WriteLine("=================== TEST START ===================");
DeleteData();
Console.WriteLine(">> Storage test start...");
Stopwatch sw = Stopwatch.StartNew();
InsertData(cs);
sw.Stop();
Console.WriteLine("<< Store data seconds: " + sw.ElapsedMilliseconds / 1000 + " ( " + sw.ElapsedMilliseconds + " miliseconds)");
Console.WriteLine(">> Query test start...");
sw = Stopwatch.StartNew();
QueryData();
sw.Stop();
Console.WriteLine("<< Query data seconds: " + sw.ElapsedMilliseconds / 1000 + " ( " + sw.ElapsedMilliseconds + " miliseconds)");
Console.WriteLine(">> Delete test start...");
sw = Stopwatch.StartNew();
DeleteData();
sw.Stop();
Console.WriteLine(">> Delete data seconds: " + sw.ElapsedMilliseconds / 1000 + " ( " + sw.ElapsedMilliseconds + " miliseconds)");
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
8,測試。在上面的代碼中,有三個輔助方法插入數據,查詢數據,刪除數據。然后在 main()函數中分別調用它們,並對性能進行初步估算。當我們只插入10記錄時,其結果如下: