Search code examples
entity-frameworkentity-framework-6ef-code-first

Entity Framework error during update: field is required


I'm using EF 6.2.0, Code First from Database, in a .net 4.5.2 environment. I have this DbSet:

<Table("Firebird.PLANT4")>
Partial Public Class PLANT4
  <Key>
  <DatabaseGenerated(DatabaseGeneratedOption.None)>
  Public Property ID_PLANT4 As Integer

  Public Property STATUS As Integer

  <Required>
  <StringLength(20)>
  Public Property DESCRIPTION1 As String

  Public Property COUNTER As Long

  Public Property RESET_COUNTER As Integer
End Class

When I execute this code:

Using dbContext As New DbModel
  dbContext.Database.Connection.ConnectionString = GetFbConnectionString()
  dbContext.Database.Connection.Open()

  Dim plant As PLANT4 = dbContext.PLANT4.Find(1)
  plant.RESET_COUNTER = 1
  dbContext.SaveChanges()
End Using

I get the error: "DESCRIPTION1 field is required". The exception is throwing during SaveChanges. I can't understand where the problem is, as if I watch "plant" in debug, all fields are there (ID_PLANT4 = 1 is an existing row), and DESCRIPTION1 in particular is not Nothing.

I can simply remove the "Required" attribute and it works, but the attribute is a consequence of the db column not allowing nulls, so I don't think this is the right way to go.

I can even add this line of code, just after the "Using" statement:

dbContext.Configuration.ValidateOnSaveEnabled = False

and it works, but again I don't think this is the right way to go.

What is the reason of this behavior?


Solution

  • Eventually I find that the problem is: field DESCRIPTION1 is populate by default with 20 spaces. It is not null, but it is a string formed only by spaces. For an unknown reason, during validation this string is treated by EF like null, and an exception is thrown because it's a required field.

    "Required" attribute is not needed, but I generate my POCO classes by "Code First from Database", so if a VARCHAR field is declared as "not null" it is automatically generated with the "Required" attribute. Now I think it's better allowing nulls for VARCHAR columns.