2009-09-03 85 views
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); 

,然後用更新流程繼續...

+0

a。分配值之前的if語句是爲了防止上下文將記錄標記爲已更新,如果這些值實際上沒有更改。 b被約瑟處理得很好。 – 2009-09-03 20:14:06

回答

6

的方式你這樣做你需要的if語句是唯一的原因新的它,並插入它,所以我會使用if語句只是爲了。

我會做這個:

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(); 
      db.Employees.InsertOnSubmit(oldEmployee); 
     } 

     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; 
    } 
} 

我也認爲有辦法一個對象的屬性映射到其他,但我想不起來了的時刻。它可能無法用於你想要做的事情,因爲看起來你在稍後用ModifiedDate和EmployeeID做了其他事情。

+0

你有沒有前映射? – ari 2009-09-04 05:11:26