[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記錄時,其結果如下:

轉載于:https://www.cnblogs.com/kesalin/archive/2012/03/09/entityframework.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377669.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377669.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377669.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c++ cdi+示例_C ++“和”關鍵字示例

c cdi示例"and" is an inbuilt keyword that has been around since at least C98. It is an alternative to && (Logical AND) operator and it mostly uses with the conditions. “ and”是一個內置關鍵字&#xff0c;至少從C 98起就存在。 它是&&am…

Python上個手

Python&#xff0c;由吉多范羅蘇姆&#xff08;Guido van Rossum&#xff09;在1989打發圣誕節放假時間的一門“課余”編程項目&#xff0c;至今已有二十多年的歷史&#xff0c;語法簡潔清晰&#xff0c;深受喜愛&#xff1b; 小窺 # 查看版本 python -V # 輸出 print "he…

十、美化界面

一、背景圖片 二、透明化處理 BackColor—web—Transparent 三、數據庫建表語句 數據庫 USE [fiber_yy] GO /****** Object: Table [dbo].[yy_user_record] Script Date: 06/20/2022 18:54:48 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADD…

如何寫出優美的代碼(二)

&#xff08;本文思想基本來自于經典著作《重構》一書&#xff09; 上一篇 http://www.cnblogs.com/ceys/archive/2012/03/05/2379842.html#commentform 上一篇文章主要講了怎么給函數整容。現在我們大家基本上都使用面向對象語言&#xff0c;什么樣的“對象”才是優美的呢&…

轉:鏈表相交問題 詳解

源地址&#xff1a;http://blog.163.com/bbluesnow126/blog/static/27784545201251051156817/ 鏈表相交問題 2012-06-10 17:15:37| 分類&#xff1a; 算法 | 標簽&#xff1a;微軟面試題 |字號 訂閱 1、如何判斷一個單鏈表有環 2、如何判斷一個環的入口點在哪里 3、如何知…

VS 如何修改C++編譯標準

第一步&#xff0c;打開項目資源管理器的屬性頁面 第二步&#xff0c;選擇配置屬性->C/C>語言->C語言標準 第三步&#xff0c;選擇合適的標準&#xff0c;一般來說選最新即可

維吉尼亞密碼和一次性密碼本_密碼學中的一次性密碼

維吉尼亞密碼和一次性密碼本The One-time Pad cipher is almost similar to the Vernam cipher, as, like the vernam cipher, this cipher technique also encrypts the plain text by working on the binary level of the text. The only difference between the two is that…

十一、紡織面料下架功能的實現

一、數據庫 數據庫仍用yy_textile表&#xff0c;前幾篇博文都敘述過這里就不再敘述 在fiber_yy數據庫下創建yy_textile表 初始數據庫信息 二、頁面 admin_undercarriage 三、代碼實現 admin_undercarriage using System; using System.IO; using System.Data; using S…

svg和canvas的應用場景分析【轉載】

原文地址&#xff1a;http://blogs.msdn.com/b/weizhong/archive/2011/07/16/canvas-svg.aspx 思考什么時候使用Canvas 和SVG wzhong 15 Jul 2011 9:07 PM 0HTML5 Canvas 和 SVG 是 IE9 中引入的兩項令人激動的圖形功能。上周在拉斯維加斯舉辦的 MIX11 大會對這兩個功能進行了介…

【C++grammar】文件系統以及path類使用

目錄1.文件系統概述1、關于路徑2、如何將某個路徑下的所有文件遞歸地找出來&#xff1f;2.路徑類及操作1、path類的成員函數2、path類的非成員函數示例1&#xff1a;展示C17中的path對象的用法示例2&#xff1a;展示Path類中用于分解路徑成分的函數示例3&#xff1a;展示path相…

scala hashmap_如何在Scala中將Hashmap轉換為Map?

scala hashmapLets first understand what are maps and hashmaps? 首先讓我們了解什么是map和hashmap &#xff1f; map in Scala is a collection that stores its elements as key-value pairs, like a dictionary. Scala中的map是一個集合&#xff0c;將其元素存儲為鍵值…

十二、所有功能實現效果演示

一、系統項目架構 Ⅰ&#xff0c;fiber_yy數據庫下有五張表 yy_admin&#xff1a;管理員登錄賬號和密碼 yy_textile&#xff1a;紡織面料數據信息 yy_textile_record&#xff1a;用戶購買紡織面料信息所存儲的面料流水信息 yy_user&#xff1a;用戶登錄注冊信息 yy_user_reco…

行業軟件之PTV微觀軟件VISSIM4.3 5.0 5.1 5.2 5.3 5.4下載和相關資料

他是干什么的&#xff1a;http://baike.baidu.com/view/3656765.htm 中國代理銷售的公司的網址&#xff1a;辟途威交通科技(上海)有限公司 官網&#xff1a;http://www.ptvchina.cn/ 看看視頻中軟件的運行效果&#xff1a;http://v.youku.com/v_show/id_XMzExMjg1MDEy.html 如何…

一、單個神經元網絡構建

一、本人使用編譯器為Jupyter Notebook&#xff0c;tensorflow版本為1.13.1 import tensorflow as tf print(tf.__version__) """ 1.13.1 """二、訓練單個神經元網絡 x為-1.0, 0.0, 1.0, 2.0, 3.0, 4.0 y為-3.0, -1.0, 1.0, 3.0, 5.0, 7.0 人用…

ruby 生成隨機字符串_Ruby程序生成隨機數

ruby 生成隨機字符串產生隨機數 (Generating random number) The task is to generate and print random number. 任務是生成并打印隨機數。 Generating random numbers means that any number can be provided to you which is not dependent on any pre-specified condition…

leetcode 322. 零錢兌換 思考分析

目錄1、題目2、思路分析3、參考鏈接1、題目 給定不同面額的硬幣 coins 和一個總金額 amount。編寫一個函數來計算可以湊成總金額所需的最少的硬幣個數。如果沒有任何一種硬幣組合能組成總金額&#xff0c;返回 -1。 你可以認為每種硬幣的數量是無限的。 提示&#xff1a; 1 …

linux上的英文字體monospace可以在windows用嗎?

linux的字體都是開源的&#xff0c;應該可以官方下載本地下載轉載于:https://www.cnblogs.com/52linux/archive/2012/03/14/2396103.html

Flash Builder 創建CSS

1.global 選擇器將樣式應用于所有控件 在 Flash Builder 中創建新MXML 文件并切換到設計模式 屬性視圖右側的外觀視圖可更改外觀 Flash Builder 自動創建CSS 文件 CSS 文件有2 個命名空間&#xff1a; s 指 Spark 組件 mx 指 MX 組件 1. Global 與Application 選擇器 global …

ruby打印_Ruby程序打印數字的力量

ruby打印Ruby中數字的冪 (Power of a number in Ruby) The task to develop a program that prints power of a number in Ruby programming language. 開發可以用Ruby編程語言打印數字冪的程序的任務。 If we want to calculate the power of a number manually then we have…

二、訓練fashion_mnist數據集

一、加載fashion_mnist數據集 fashion_mnist數據集中數據為28*28大小的10分類衣物數據集 其中訓練集60000張&#xff0c;測試集10000張 from tensorflow import keras import tensorflow as tf import matplotlib.pyplot as plt import numpy as npfashion_mnist keras.data…