Null Integer Field

Posts   
 
    
Posts: 134
Joined: 04-Mar-2005
# Posted on: 22-Jul-2005 01:05:27   

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?

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39933
Joined: 17-Aug-2003
# Posted on: 22-Jul-2005 08:01:51   

If you want NULL in a NEW entity, for a field Foo, don't set Foo to a value simple_smile So not 0, not NULL, just not set it to a value, which means the field isn't inserted, which results to NULL.

Frans Bouma | Lead developer LLBLGen Pro
Posts: 134
Joined: 04-Mar-2005
# Posted on: 22-Jul-2005 20:48:08   

Otis wrote:

If you want NULL in a NEW entity, for a field Foo, don't set Foo to a value simple_smile 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...

confused

Posts: 134
Joined: 04-Mar-2005
# Posted on: 19-Aug-2005 01:50:37   

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

I think I'll do something similar for handling dates. I'm using the DevExpress controls and running into the same problem as omar (http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=2207) and HaulMark (http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=2568)