Reputation: 1717
I'm having an issue with setting a default value on a string using Fluent Nhibernate. I have a database with varchar field that is not null, and I am trying to construct some objects and then update them to the database, however as a string can be null within .Net, I'm having a problem when I try to update the entity to the database.
I've Googled for a solution, but so far, the word "Default" seems to appear in a lot of related topics so it's hard to filter down what I actually want.
What I'd like to do is set the default on the mapping to be an empty string so that the calling code doesn't need to know that the database field is not nullable. As yet, just setting the mapping as .Default(string.Empty) hasn't worked, so I'm guessing I'm doing it wrongly. I can fix this by adding a constructor call to set the field to an empty string on the entity constructor, but that feels quite nasty, so I'm looking for a better way to do it if there is one out there.
So, some of the code...
Entity Property (pretty vanilla):
public virtual string Notes { get; set; }
and Mapping:
Map(m => m.Notes).Default(string.Empty).Not.Nullable();
I've also tried using a literal empty string .Default(""), and putting the Not.Nullable() before the default and neither approach has worked either.
At the moment, I'm going to use the constructor call so that this isn't blocking me, but I'd like to find a better way to do it if there is one.
Any help greatly appreciated.
Upvotes: 3
Views: 4794
Reputation: 6122
I also had problems setting an empty string as default value. Note that i am using SQLite. After some investigation, it seems that FluentNHibernate is generating a "wrong" SQL statement in respect to the fluent mapping.
Lets take
Map(m => m.Notes).Default(string.Empty).Not.Nullable();
or
Map(m => m.Notes).Default("").Not.Nullable();
from your example. We would expect this SQL:
Notes TEXT DEFAULT "" NOT NULL
but it generates
Notes TEXT
Its obviously omitting "" as a default value. Using
Map(m => m.Notes).Default(" ").Not.Nullable();
results in
Notes TEXT DEFAULT NOT NULL
whats even worse, because its invalid SQL because "" is missing.
Using
Map(m => m.Notes).Default("\"\"").Not.Nullable();
generates the correct SQL like
Notes TEXT DEFAULT "" NOT NULL
actually using an empty string as default value.
Upvotes: 4
Reputation: 15313
Set the value of your property to the empty string in the constructor of your object.
.Default(string.Empty)
is used for schema generation only. This will not default the value of this property to the empty string in your object.
You could also use DynamicInsert()
in your mapping. Therefore it would use the database default if you aren't explicity setting this to a value.
dynamic-insert (optional, defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
Upvotes: 1