3
這是我用來保存與LINQ記錄方式:(我的Q是如下圖)保存新的或更新的記錄存在與LINQ
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee = (from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
oldEmployee.BirthDate = employee.BirthDate;
oldEmployee.WorkRole = employee.WorkRole;
oldEmployee.CurrentFlag = employee.CurrentFlag;
oldEmployee.HireDate = employee.HireDate;
...
db.Employees.InsertOnSubmit(oldEmployee);
}
else
{
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
}
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
我的問題是:
一個。是if語句nesccery?爲什麼不在沒有 檢查的情況下進行分配? mybe如果塊需要更多的CPU ..
b。爲什麼要指定新的記錄塊和更新塊?
當記錄是新會做
db.Employees.InsertOnSubmit(oldEmployee);
,然後用更新流程繼續...
a。分配值之前的if語句是爲了防止上下文將記錄標記爲已更新,如果這些值實際上沒有更改。 b被約瑟處理得很好。 – 2009-09-03 20:14:06