EF&LINQ開發實戰 Part3

  • 2727
  • 0
  • EF
  • 2011-02-06

EF&LINQ開發實戰 Part3

<Linq To SQL>

對資料庫的操作不外乎C(建立)、R(讀取)、U(修改)、D(刪除)…,學習EF也不免其俗的要對EF進行CRUD操作。

1.首先建立Employee Table:

Snap4

2.產生全域連線字串(dbConn)及DataContext(dc):

 

	static string dbConn = @"Data Source=XXX.mdf;Integrated Security=True;User Instance=True;";
static DataContext dc = new DataContext(dbConn);

3.產生Employee(CEmployee)類別:

	[Table(Name = "Employee")]
        public class CEmployee
        {
            [Column(IsPrimaryKey = true)]//PK
            public int ? EmpID;
            [Column]
            public string Name = "";
            [Column]
            public int Salary = 0;
        }

4.產生Create(C)方法:

	static void Create()
        {
            CEmployee emp = new CEmployee(); //new CEmployee
            emp.EmpID = 2;                   //賦予員工編號
            emp.Name = "Kiwi";               //賦予員工姓名
            emp.Salary = 10000;              //賦予員工薪水
            Table<CEmployee> Tbemp = dc.GetTable<CEmployee>();//一定要先取得Employee型別的物件集合
            Tbemp.InsertOnSubmit(emp);       //塞入一筆資料
            dc.SubmitChanges();              //確定修改
            Console.WriteLine("資料新增完成 ... ");
        }

5. 產生Read(R)方法;藉由傳入的員工編號找到該筆員工資料(EmpID==id):

	static CEmployee Read(int id)
        {
            return dc.GetTable<CEmployee>().Where(e => e.EmpID==id).FirstOrDefault(); 
        }

6.產生Update(U)方法;藉由傳入的CEmployee物件,更改Salary:

	static void Update(CEmployee emp, int UpSalary)
        {
            emp.Salary = UpSalary;
            dc.SubmitChanges();
            Console.WriteLine("資料修改完成 ... ");
        }

7.產生Delete(D)方法;藉由傳入的CEmployee物件,刪除該筆員工資料:

	static void Delete(CEmployee emp)
        {
            dc.GetTable<CEmployee>().DeleteOnSubmit(emp);
            dc.SubmitChanges();
            Console.WriteLine("資料刪除完成 ... ");
        }

主程式如下:

	static void Main(string[] args)
        {
            //C 新增
            Create();                     
            Console.WriteLine("目前共有"+dc.GetTable<CEmployee>().Count()+"筆資料");
            //R 讀取
            CEmployee emp = Read(2);       
            Console.WriteLine(emp.Name);
            Console.WriteLine("原有薪水:"+emp.Salary+"元");
            //U 修改(薪水) 
            Update(emp, 30000);            
            Console.WriteLine(emp.Name);
            Console.WriteLine("調整薪水後:" + emp.Salary); 
            //D 刪除
            Delete(emp);
            Console.WriteLine("目前共有" + dc.GetTable<CEmployee>().Count() + "筆資料");
            Console.Read();
        }

結果:

Snap5