linq學習筆記

highhand發表於2021-09-09

試用了幾天linq,感覺確實方便,而且生成的sql也還不錯,下面是幾點體會

1.幾種常見的等效select寫法
var s = from c in ctx.T_Users select new { c.F_Name, c.F_Sex, c.F_Birthday, c.F_ID }
這種寫法對於初學者來說,最容易理解
 
var s = ctx.T_Users.Select(p => new { p.F_Name, p.F_Sex, p.F_Birthday, p.F_ID })
這種寫法利用T_Users這一泛型Table集合的擴充套件方法

var s = ctx.T_User.Select(p => new { p.F_Name, p.F_Sex, p.F_Birthday, p.F_ID })
這種寫法幾乎與第二種寫法完全一樣,看清楚,這裡T_User而不是T_Users!這是直接利用T_User的擴充套件方法

經除錯,這三種方法生成的sql語句完全一樣

2.快速更新資料庫結構
如果資料庫的表結構或檢視結構等物件做了改動,而又不想在dbml視覺化環境裡,刪除原來的物件,再拖拉同樣的物件到可視環境中,有一個相對簡單點的辦法,利用sqlmetal.exe工具(開始-->程式-->Microsoft Visual Studio 2008-->Visual Studio Tools-->Visual Studio 2008 Command Prompt)

該工具可方便快速的將整個資料庫的表,檢視,儲存過程生成cs類,完整引數如下:
Microsoft (R) Database Mapping Generator 2008 version 1.00.21022
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

SqlMetal [options] []

  Generates code and mapping for the LINQ to SQL component of the .NET framework. SqlMetal can:
  - Generate source code and mapping attributes or a mapping file from a database.
  - Generate an intermediate dbml file for customization from the database.
  - Generate code and mapping attributes or mapping file from a dbml file.

Options:
  /server:             Database server name.
  /database:           Database catalog on server.
  /user:               Login user ID (default: use Windows Authentication).
  /password:       Login password (default: use Windows Authentication).
  /conn:  Database connection string. Cannot be used with /server, /database, /user or /password options.
  /timeout:         Timeout value to use when SqlMetal accesses the database (default: 0 which means infinite).

  /views                     Extract database views.
  /functions                 Extract database functions.
  /sprocs                    Extract stored procedures.

  /dbml[:file]               Output as dbml. Cannot be used with /map option.
  /code[:file]               Output as source code. Cannot be used with /dbml option.
  /map[:file]                Generate mapping file, not attributes. Cannot be used with /dbml option.

  /language:       Language for source code: VB or C# (default: derived from extension on code file name).
  /namespace:          Namespace of generated code (default: no namespace).
  /context:            Name of data context class (default: derived from database name).
  /entitybase:         Base class of entity classes in the generated code (default: entities have no base class).
  /pluralize                 Automatically pluralize or singularize class and member names using English language rules.
  /serialization:

                 May be a SqlExpress mdf file, a SqlCE sdf file, or a dbml intermediate file.

Create code from SqlServer:
  SqlMetal /server:myserver /database:northwind /code:nwind.cs /namespace:nwind

Generate intermediate dbml file from SqlServer:
  SqlMetal /server:myserver /database:northwind /dbml:northwind.dbml /namespace:nwind

Generate code with external mapping from dbml:
  SqlMetal /code:nwind.cs /map:nwind.map northwind.dbml

Generate dbml from a SqlCE sdf file:
  SqlMetal /dbml:northwind.dbml northwind.sdf

Generate dbml from SqlExpress local server:
  SqlMetal /server:.sqlexpress /database:northwind /dbml:northwind.dbml

Generate dbml by using a connection string in the command line:
  SqlMetal /conn:"server='myserver'; database='northwind'" /dbml:northwind.dbml

個人感覺,直接生成map和cs檔案比較實用

比如生成LINQDB.MAP和LINQDB.CS後,如何使用呢?往下看

將LINQDB.MAP 複製到 網站根目錄/DATAMAP目錄下(當然DATAMAP這個名字,你可以隨意指定)
將LINQDB.CS 複製到 /APP_CODE/目錄下

為了方便以後程式碼重用,我習慣在APP_CODE目錄下建立一個公用的類檔案CONFIG.CS(用來放一些常用的公共方法)

///


/// Summary description for CONFIG
///

public static class CONFIG
{
    public static Linqdb GetDBContext(string ConnString)
    {
        String path = HttpContext.Current.Server.MapPath("~/DATAMAP/LINQDB.MAP");
        XmlMappingSource xms = XmlMappingSource.FromXml(File.ReadAllText(path));
        Linqdb ctx = new Linqdb(ConnString, xms);
        return ctx;
    }

    public static Linqdb GetDBContext()
    {
        String path = HttpContext.Current.Server.MapPath("~/DATAMAP/LINQDB.MAP");
        XmlMappingSource xms = XmlMappingSource.FromXml(File.ReadAllText(path));
        Linqdb ctx = new Linqdb(ConfigurationManager.ConnectionStrings["ConnStr"].ToString(), xms);
        return ctx;
    }
}

這是二個主要方法,用來得到DataContext物件的例項

終於進到關鍵地方了,以下是使用的程式碼:

protected void Page_Load(object sender, EventArgs e)
{
    ShowData();
}

void ShowData()
{
    using (Linqdb ctx = CONFIG.GetDBContext())
    {
        var s = ctx.T_User.Select(p => new { p.F_Name, p.F_Sex, p.F_Birthday, p.F_ID });
        this.GridView1.DataSource = s;
        this.GridView1.DataBind();          
    }
   
}  

值得注意的是:如果用metasql.exe生成的cs檔案,裡面不會有"表名s"這個類,而在視覺化環境中,拖放出來的表,除會生成"表名"這個類外,還會同步生成一個"表名s"的類

即:假設資料庫中有一個表T_User,用metasql.exe生成的cs檔案中,僅包含T_User這個對應該表的類,而在視覺化環境中,除生成T_User類外,還會有一個T_Users類,程式碼類似下面這樣:
public System.Data.Linq.Table T_Users
{
 get
 {
  return this.GetTable();
 }
}

呵呵,今天就寫這麼多,以後有好的心得再接著寫

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/810/viewspace-2809024/,如需轉載,請註明出處,否則將追究法律責任。