Is it by design that setting an integer field on a new record/entity to 0 will attempt to write that 0 to the DB? The reason I ask is that I'm getting exceptions on my foreign keys (which are ints) when setting to 0 (which I do in this case because the foreign key is user-selectable).
I can test my foreign keys for dbValue = Nothing and CurentValue = 0 and explicitly SetnewFieldValue(<field>, Nothing) just before save but I'm wondering whether this is necessary?
If you want NULL in a NEW entity, for a field Foo, don't set Foo to a value So not 0, not NULL, just not set it to a value, which means the field isn't inserted, which results to NULL.
If you want NULL in a NEW entity, for a field Foo, don't set Foo to a value So not 0, not NULL, just not set it to a value, which means the field isn't inserted, which results to NULL.
Well I'd have to write a special case for this as I re-bind my controls on postback. I figured it would be easier just to let the re-binding happen (which is what sets the value to 0) and then handle the case later...
I have come up with a pretty simple solution to this which I think will do what I want. This is only a problem for nullable foreign keys so I've added the following code to the beginning of the SetNewFieldValue for each entity:
If Me.Fields(fieldIndex).IsForeignKey Then
If Me.Fields(fieldIndex).IsNullable AndAlso Me.Fields(fieldIndex).IsNull Then
If value.ToString = "0" OrElse value.ToString = String.Empty Then
'Don't a null foreign key to be set to empty value ('' or 0)
Return False
End If
End If
End If