LinQ初體驗

摘要:LinQ初體驗

步驟1. 建立一個Linq  to  sql 的類別  並建立連線將您要的資料表拖入視窗內。

步驟2.

####################################################################

using System.Linq;

using System.Configuration;

########################  宣告全域變數  #############################

 string connectString = ConfigurationManager.ConnectionStrings["NorthConnectionString"].ConnectionString;
 orderDataContext data;

 

########################       查詢     ############################

   data = new orderDataContext(connectString);
        var query = from oemp in data.emp
                    select oemp;

        litList.Text = "";
        foreach (var c in query)
            litList.Text+=("--EmpID:" + c.mem_id + "  Name:" + c.mem_name + "    Value:" + c.mem_value + "--<br/>");

        data.Dispose();

 

 

 

########################     新增    ############################

 data = new orderDataContext(connectString);

         emp oemp = new emp();
         oemp.mem_name = txtName.Text;
         oemp.mem_value = Convert.ToInt16( txtValue.Text);

         data.emp.InsertOnSubmit(oemp);
         data.SubmitChanges();
        data.Dispose();

 

 

########################     修改    ############################

  data = new orderDataContext(connectString);
       var query = from oemp in data.emp
                    where oemp.mem_id == Convert.ToInt32(txtID2.Text)
                    select oemp;

       query.First().mem_name = txtName2.Text;
       query.First().mem_value = Convert.ToInt16(txtValue2.Text);

       data.SubmitChanges();
       data.Dispose();

 

 

########################   刪除   ############################

  data = new orderDataContext(connectString);
        var query = from oemp in data.emp
                    where oemp.mem_id == Convert.ToInt32(txtID3.Text )
                    select oemp;

        if (query.Count() > 0)
        {
           // data.emp.DeleteAllOnSubmit(query);  //刪除多筆
            data.emp.DeleteOnSubmit(query.First());
            data.SubmitChanges();
        }
        data.Dispose();