views:

102

answers:

3

Hi,

I'm looking for a point in the right direction to solving this problem.

I am being passed an object from the ui.

One of the values is for a foreign key (an int which allows nulls). The value being sent is -1 which signifies that the value has not been set by the user.

How can I write this object to the db setting the foreign key to a null value.

I am using NHibernate with fluent for the mapping.

Also, is this good practice? Or am I better setting up a default value to fall back on.

Any help much appreciated.

A: 

I guess first thing to check is the default value of -1 given to that column in the database.

Sadly I don't know enough about NHibernate on what to look for there.

mcauthorn
+2  A: 

Pseudocode:

class Entity {
   public int Id {get; private set;}
   public int? NullableValue {get;set;}
}
...
if (valueReceived == -1)
  entity.NullableValue = null;
...
session.Update(entity);
Mauricio Scheffer
+1  A: 

Without seeing your map file to be more specific, I'd first suggest to add the Nullable() field to your mapped reference:

// nullable
Reference(x => x.ReferencedEntity).Nullable();

Then I believe make your common object use a nullable type:

public virtual int? ForeignKeyFieldId { get; set; }

Finally, I'd convert your -1 to null as soon as the UI hands over your object. There's no point having an entity travel around with misleading data if it can be avoided.

After that simply updates should work fine.

ddc0660
Thanks. This will be handy knowledge as I intend to use fluent more. On this occasion though I've decided to go with assigning a default key.