2012-08-02 56 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