EF&LINQ開發實戰 Part4

  • 1432
  • 0

EF&LINQ開發實戰 Part4

       其實很早就嘗試利用EDM在小專案開發上,但是沒有機會去摸熟EF,用起來實在綁手綁腳,

在時間不允許下又改回傳統資料庫連接方式,在本次修鍊中,發現了EntityClient這個資料類別,

利用這個類別可以讓我們在使用EDM的同時,也可以使用類似ADO.NET方式取得資料內容。

本次修鍊是仿傳統模式利用DataReader接收資料,步驟方式盡量與傳統Ado.net相似。

1.首先建立一個EDM(NewEntities) :

Snap6

2.在程式碼中using System.Data.EntityClient :

3. coding:

   3-1. new EntityConnection

   3-2. new EntityCommand

   3-3. 撰寫SQL命令,必須使用Entity SQL

   3-4. new EntityDataReader(範例是使用EntityDataReader 接收資料)


	using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
// using System.Data.EntityClient;
using System.Data.EntityClient;
namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            EntityConnection EC = new EntityConnection("Name=NewEntities");
            EntityCommand Ecmd = new EntityCommand();
            Ecmd.Connection = EC; 
            Ecmd.CommandType = System.Data.CommandType.Text;
            string SQL = @"Select Value V From NewEntities.Employees as V";
            Ecmd.CommandText = SQL;
            EC.Open();
            EntityDataReader EDR = Ecmd.ExecuteReader(CommandBehavior.SequentialAccess);
            while (EDR.Read())
               Console.WriteLine("EmpID:"+EDR.GetInt32(0) +" Name:"+EDR.GetString(1)+" Salary:"+ EDR.GetInt32(2));      
            EC.Close(); 
        }
    }
}

範例結果如下 :

Snap7

接收的資料,(EntityDataReader)可以使用仿DataReader.Read()方式把資料取出,

無法直接轉成DataSet Or DataTable;如果真的要轉成DataSet Or DataTable 可以參考

Hydrating a DataTable from an EntityDataReader - part 1Hydrating a DataTable from an EntityDataReader - Part 2