datacontext
datacontext型別(資料上下文)是system.data.linq命名空間下的重要型別,用於把查詢句法翻譯成sql語句,以及把資料從資料庫返回給呼叫方和把實體的修改寫入資料庫。
·datacontext提供了以下一些使用的功能: ·
以日誌形式記錄datacontext生成的sql ·
執行sql(包括查詢和更新語句) ·
建立和刪除資料庫
datacontext是實體和資料庫之間的橋梁,那麼首先我們需要定義對映到資料表的實體。
定義實體類
以northwind資料庫為例,上述customers類被對映成乙個表,對應資料庫中的customers表。然後在型別中定義了三個屬性,對應表中的三個字段。其中,customerid欄位是主鍵,如果沒有指定column特性的name屬性,那麼系統會把屬性名作為資料表的欄位名,也就是說實體類的屬性名就需要和資料表中的欄位名一致。
現在,建立乙個asp.net頁面,然後在頁面上加入乙個gridview控制項,使用下面的**進行繫結資料:
using system.data.linq;
datacontext ctx = new datacontext("server=***;database=northwind;uid=***;pwd=***");
tablecustomers = ctx.gettable();
gridview1.datasource = from c in customers where c.customerid.startswith("a") select new ;
gridview1.databind();
使用datacontext型別把實體類和資料庫中的資料進行關聯。你可以直接在datacontext的構造方法中定義連線字串,也可以使用idbconnection:
using system.data.sqlclient;
idbconnection conn = new sqlconnection("server=***;database=northwind;uid=***;pwd=***");
datacontext ctx = new datacontext(conn);
之後,通過gettable獲取表示底層資料表的table型別,顯然,資料庫中的customers表的實體是customer型別。隨後的查詢句法,即使你不懂sql應該也能看明白。從customers表中找出customerid以「a」開頭的記錄,並把customersid、name以及city封裝成新的匿名型別進行返回。
結果如下圖:
強型別datacontext
public partial class northwinddatacontext : datacontext
public northwinddatacontext(string connection) : base(connection) }
強型別資料上下文使**更簡潔:
northwinddatacontext ctx = new northwinddatacontext("server=***;database=northwind;uid=***;pwd=***");
gridview1.datasource = from c in ctx.customers where c.customerid.startswith("a") select new ;
gridview1.databind();
linq中文教程 二
what s linq?language integrated query 是也。說得再明白一些,這是程式語言的一種新特性,能夠將資料查詢語句整合到程式語言中。目前,linq 支援的語言有 c 和vb。為啥會有 linq 主要還是因為現在的資料格式越來越多,資料庫 xml 陣列 雜湊表 每一種都有自...
linq中文教程 五
自動屬性 public class person public int age public person person p new person p.username aa console.writeline p.username 意義不是很大,純粹解決機械勞動。編譯器自動為你生成get set操...
linq中文教程 十
使用dbdatareader資料來源 using system.data.sqlclient var conn new sqlconnection server database northwind uid pwd var ctx new datacontext conn var cmd new s...