2012-08-02 71 views
0

我試圖獲取記錄並將其存儲起來,以便以後在頁面上發生錯誤時使用。無法強制執行LINQ評估

此代碼用於創建/編輯。所以我從View Model中獲取數值並映射到db實體:

Dim objExistingSupplier As SUPPLIER = db.SUPPLIER.Single(Function(e) e.SUPPLIER_ID = Supplier.SUPPLIER_ID) 
objPermStaffAction = objExistingSupplier 
objSupplier = Mapper.Map(Of SupplierViewModel, SUPPLIER)(Supplier, objExistingSupplier) 

從我所瞭解的情況來看,.Single應該強制評估。但是,在映射發生後,屬性在objPermStaffAction對象中丟失/更改。有人能解釋我做錯了什麼嗎?

這裏是全功能:

Private Function SaveSupplier(Supplier As SupplierViewModel) As ActionResult 
     Dim objSupplier, objPermStaffAction As SUPPLIER 
     If Supplier.SUPPLIER_ID = 0 Then 
      objSupplier = Mapper.Map(Of SupplierViewModel, SUPPLIER)(Supplier) 
     Else 
      Dim objExistingSupplier As SUPPLIER = db.SUPPLIER.Single(Function(e) e.SUPPLIER_ID = Supplier.SUPPLIER_ID) 
      objPermStaffAction = objExistingSupplier 
      objSupplier = Mapper.Map(Of SupplierViewModel, SUPPLIER)(Supplier, objExistingSupplier) 
     End If 

     If ModelState.IsValid Then 
      If Supplier.SUPPLIER_ID = 0 Then 
       objSupplier.CREATED_BY = Session("AppUserID") 
       db.SUPPLIER.Add(objSupplier) 
      Else 
       objSupplier.UPDATED_BY = Session("AppUserID") 
       UpdateModel(objSupplier) 
      End If 

      Try 
       db.SaveChanges() 
       Return RedirectToAction("Index") 
      Catch ex As Exception 
       If InStr(ex.InnerException.InnerException.Message, "PRSNL.SUPPLIER_UK") > 0 Then 
        ModelState.AddModelError("SUPPLIER_CODE", "Supplier Code already exists. Please choose another.") 
       End If 
      End Try 

     End If 

     'This will run if an error occured 
     If Supplier.SUPPLIER_ID > 0 Then 
      Supplier = Mapper.Map(Of SupplierViewModel)(objPermStaffAction) 
     End If 
     ViewBag.YNList = Common.GetYNList 
     Return View(Supplier) 
    End Function 

回答

0

SupplierViewModel是引用類型。所以objPermStaffAction引用映射後得到更新的相同對象。

爲什麼你需要原始(未映射)對象?

+0

對不起,我明白你爲什麼會這樣做。我編輯了文字,以更好地描述場景。我還在尋找一個解釋爲什麼第2行的objPermStaffAction在第3行映射後沒有保留它的屬性值的答案。 – btbond 2012-08-02 03:24:53

+0

@btbond我相應地更新了答案。 – k0stya 2012-08-02 03:37:50

+0

在編輯窗體上,我顯示只讀審計信息(created_by,create_dt,updated_by,update_dt)。如果發生驗證錯誤,則在重新加載表單時,這些值將消失。我會發布整個功能。 – btbond 2012-08-02 12:46:15