從學習EF到ORM的思考

ORM ,不管是EF,hibernate,都是起到一個映射數據庫對象的作用

在映射的基礎上,提供很多功能和特性,比如,

數據庫對象的class化訪問

很多數據庫本身沒有提供的函數

直接使用編程框架提供的功能 

等等

不過我也有自己的思考,做爲一個以前從事過長時間的數據庫編程人員來說,總是感覺ORM麻煩,可能是人的習慣問題吧

需要一段時間的體驗,才能知道優缺點,在這之前,還是抱着一定的懷疑態度  

 

EF代碼的幾種形式

  1. EntityClient+EntitySQL

    示例代碼:

string city = "London";

using (EntityConnection cn = new EntityConnection("Name=Entities"))

{

cn.Open();

EntityCommand cmd = cn.CreateCommand();

cmd.CommandText = @"SELECT VALUE c FROM Entities.Customers AS c WHERE

c.Address.City = @city";

cmd.Parameters.AddWithValue("city", city);

DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

while (rdr.Read())

Console.WriteLine(rdr["CompanyName"].ToString());

rdr.Close();

}

 

  1. ObjectService+EntitySQL

在有EntityClient+EntitySQL這種使用方式下,使用ObjectService+EntitySQL的方式是多此一舉,不會得到任何編輯時或運行時的好處。在ObjectContext下使用EntitySQL的真正作用是將其與LINQ to Entity結合使用。具體可見下文所示。

示例代碼:

string city = "London";

using (Entities entities = new Entities())

{

ObjectQuery<Customers> query = entities.CreateQuery<Customers>(

"SELECT VALUE c FROM Customers AS c WHERE c.Address.City = @city",

new ObjectParameter("city", city)

);

 

foreach (Customers c in query)

Console.WriteLine(c.CompanyName);

}

 

  1. ObjectContext+LINQ( to Entity)

    方式一:

string city = "London";

using (Entities entities = new Entities())

{

var query = from c in entities.Customers

where c.Address.City == city

select c;

 

foreach (Customers c in query)

 Console.WriteLine(c.CompanyName);

}

    方式二:

string city = "London";

using (Entities entities = new Entities())

{

var query = entities.Customers.Where(r => r.Address.City == city);

 

foreach (Customers c in query)

 Console.WriteLine(c.CompanyName);

} 

 

如果一個應用決定了採用EF,我應該會大量的採用ObjectContext+LINQ( to Entity)

沒有別的,至少看起來順眼,其他方式的還不如直接用ADO.net

 

發佈了13 篇原創文章 · 獲贊 9 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章