<HttpPost()>
Function Edit(<Bind(Prefix:="Article")> ByVal Article As FormCollection, Optional ByVal DepartementID As Integer = 0, Optional ByVal LeverancierID As Integer = 0) As ActionResult ', ByVal ReferenceSupplierID As Integer
' Dim Art As Article = ArticleService.GetArticleById(Article.ArticleID)
Dim _toUpdateArt As Article = ArticleService.GetArticleById(Article(0))
UpdateModel(_toUpdateArt, Article)
' TryUpdateModel(Art, Article)
If LeverancierID > 0 Then
_toUpdateArt.Supplier = LeverancierService.GetLeverancierById(LeverancierID)
Else
_toUpdateArt.Supplier = Nothing 'HERE
ModelState.Remove("LeverancierID")
End If
If DepartementID > 0 Then
_toUpdateArt.Departement = DepartmentService.GetDepartmentByID(DepartementID)
Else
_toUpdateArt.Departement = Nothing 'HERE
ModelState.Remove("DepartmentID")
End If
If ModelState.IsValid Then
_toUpdateArt.EditedOn = Now
ArticleService.SaveArticle()
Return RedirectToAction("Index")
Else
ViewBag.Index = ""
ViewBag.Create = ""
' ViewBag.Edit = ""
'ViewBag.StandardValueEnabled
ViewBag.Delete = ""
ViewBag.Editable = ""
' ViewBag.LocalSearch = ""
ViewBag.Departments = DepartmentService.GetDepartments
' ViewBag.StandardValueEnabled = ""
ViewBag.MediaShow = ""
ViewData("Media") = MediaService.GetMedia.Where(Function(el) el.Reference = Domain.Common.ReferenceTo.Article And el.ReferenceID.Equals(_toUpdateArt.ArticleID)).ToList
Dim avw As New ViewModels.ArticleViewModel
With avw
.Article = _toUpdateArt
.Leveranciers = LeverancierService.GetLeveranciers.ToList.Select(Function(dl) New SelectListItem With { _
.Text = dl.RoepNaam, _
.Value = dl.LeverancierID, _
.Selected = LeverancierID = dl.LeverancierID}).ToList
.Departements = DepartmentService.GetDepartments.Select(Function(dl) New SelectListItem With { _
.Text = dl.Code, _
.Value = dl.DepartmentID, _
.Selected = DepartementID = dl.DepartmentID}).ToList
End With
Return View(avw)
End If
End Function
_toUpdateArt.Departement = Nothing and _toUpdateArt.Supplier = Nothing is to remove the optional relationship.
But it only works when i debug it and sometimes after several loops of the command, before the relation is actually removed and it’s stored in the database.
When there isn’t a breakpoint on the “function”, the Relationship will never be nulled.
Does anyone has an explanation for this and how to fix this?
If Department is already Nothing (null) then most likely setting it to Nothing will have no effect. I suspect you see it working in the debugger because the debugger accesses the property and causes it to lazy load. After this the property is no longer Nothing and so setting it to Nothing is detected as deleting the relationship.
There are a few ways to handle this: