EF&LINQ開發實戰 Part5
在這個系列Part3,我們練習對EF進行CRUD操作。這篇修練打算對EDM利用預存程序進行CRUD操作。
1.建立四個預存程序。
1-1.建立預存程序 sp_AddNewEmp 新增(C)
AS
BEGIN
insert dbo.Employees(Name,Salary) values(@Name,@Salary)
---回傳員工編號
select empid
from Employees
where empid = scope_identity()
END
GO
1-2.建立預存程序 sp_GetEmp 讀取(R)
AS
BEGIN
Select * from Employees
END
1-3.建立預存程序 sp_SetSalary 修改(U)
AS
BEGIN
Update dbo.Employees set Salary =@Salary where EmpID=@EmpID
END
GO
1-4.建立預存程序 sp_DelEmp 刪除(D)
AS
BEGIN
Delete from Employees where EmpID=@EmpID
END
2.EDM加入這四個方法。
2-1.從資料庫更新模型
2-2.選取物件;選取剛剛新增的四個預存程序。
2-3.函式匯入
2-3-1.匯入sp_AddNewEmp (函數名稱:AddNewEmp)。
2-3-2.匯入sp_GetEmp (函數名稱:GetEmp)。
2-3-3.匯入sp_SetSalary (函數名稱:SetSalary )。
2-3-4.匯入sp_DelEmp(函數名稱:DelEmp);操作相似所以無截圖。
2-4 Coding:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
int newEmpID;
using (NewEntities NE = new NewEntities())
{
//新增(C)
ObjectResult<int?> result = NE.AddNewEmp("Kiwi", 10000);
newEmpID = result.FirstOrDefault().Value;
Console.WriteLine("新進員工編號:" + newEmpID.ToString());
//讀取(R)
var allEmp = NE.GetEmp();
foreach (Employees e in allEmp)
Console.WriteLine("EmpID:" + e.EmpID + " Name:" + e.Name + " Salary:" + e.Salary);
//更新(U)
NE.SetSalary(newEmpID, 50000);
Console.WriteLine("調薪完成");
} //Entities有Cache所以用using(){},避免抓到舊資料
using (NewEntities NE = new NewEntities())
{
//讀取(R)
var allEmp = NE.GetEmp();
foreach (Employees e in allEmp)
Console.WriteLine("EmpID:" + e.EmpID + " Name:" + e.Name + " Salary:" + e.Salary);
//刪除(D)
NE.DelEmp(newEmpID);
Console.WriteLine("刪除完成");
//讀取(R)
allEmp = NE.GetEmp();
foreach (Employees e in allEmp)
Console.WriteLine("EmpID:" + e.EmpID + " Name:" + e.Name + " Salary:" + e.Salary);
}
}
}
}
2-5結果: