如果页面上发生错误,我正在尝试获取记录并将其存储以供以后使用。
此代码用于创建/编辑。所以我从视图模型中获取值并映射到数据库实体:
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