I have inherited an application and have made alterations that use Entity Framework.
The alterations were creating a CRUD for an existing table. I've used the MVC scaffolding for creating an controller and views. All works fine except Create.
On investigation I found that the table I'm creating the CRUD code for has three columns an autonumbered primary column (ccID
), a nvarchar(50)
column (ClosureCode
) and a bit column (ccRedundant
- default 0). The ID column has a seed of 1 and increment of 1 yet it has two records with values:
ccID ClosureCode ccRedundant
-----------------------------------
-1 Not Set False
0 Not Applicable False
followed by other records.
The scaffolding code passes 0 as the ID for a new record and as such ModelState.IsValid
is always False and no new records are saved. Edit, Update and Delete work fine.
I've tried setting the value of ID to -2 and Integer.MaxValue
before posting but the save still fails at the ModelState.IsValid
which is never true.
The scaffolding code is as follows:
' POST: ClosureCodes/Create
'To protect from over-posting attacks, please enable the specific properties you want to bind to, for
'more details see https://go.microsoft.com/fwlink/?LinkId=317598.
<HttpPost()>
<ValidateAntiForgeryToken()>
Function Create(<Bind(Include:="ccID,ClosureCode,ccRedundant")> ByVal tblClosureCode As tblClosureCode) As ActionResult
If ModelState.IsValid Then
Try
db.tblClosureCodes.Add(tbClosureCode)
db.SaveChanges()
Return RedirectToAction("Index")
Catch ex As Exception
ErrorLogging.LogExceptionToLogFile(thisClass, "Create", ex)
ViewData("Message") = ErrorLogging.ErrorString(thisClass, "Create", ex, ex.InnerException)
Return RedirectToAction("Error")
End Try
End If
Return View(tblClosureCode)
End Function
The only changes I made to the generated code was to add a try catch around the save bit with a method to log any exceptions and redirect to a custom error page with the error in viewData.
Am I right in thinking that the presence of a record with ccID 0 is the reason why the Created record will not save? Is there a way around this.
UPDATE
Properties for ccID column in tblClosureCodes as requested: