[EF在VS2010中应用Entity framework与MySQL

在VS2010中应用Entity framework与MySQL

罗朝辉 (http://www.cnblogs.com/kesalin/)

本文遵循“署名-非商业用途-保持一致”创作公用协议
 

本文讲述了在VS2010中使用EF与MySQL的一个简单示例。

工具安装:

1,MySQL

MySQL Community Server 

Connector/NET 6.3.5

MySQL Workbench

分别下载上面的三个软件,注意: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记录时,其结果如下:

posted @ 2012-03-09 18:00 飘飘白云 阅读(...) 评论(...) 编辑 收藏
本博客遵循 Creative Commons License “署名-非商业用途-保持一致”创作共用协议。 与我联系