Search code examples
c#.netnhibernatenhibernate-mapping

How do I set a default value with NHibernate for enums?


Given the following tables:

create table TypeAccount
(
    AccountTypeID int primary key identity(1,1),
    [Description] varchar(100) not null
)

create table Account
(
    --AccountID char(32) primary key not null,
    AccountID int primary key identity(1,1),
    AccountName varchar(50),
    AccountTypeID int foreign key references TypeAccount(AccountTypeID),
    CreateDate datetime
)

and given the following enum definition:

public enum AccountType
{
    None = 0,
    Savings = 1,
    Checking = 2
}

when I create an Account object, if I leave it's default AccountType value of AccountType.None then when writing to the database it tries to insert a 0 (this makes sense) but since we have a foreign key restriction on the table then an exception is thrown. We need to insert either null or a value that exists in the referenced table.

My question is: is it possible with NHibernate to say something like "if my enum was not set, then write null to the database for that column?"


Solution

  • You could add the corresponding value to your AccountType table, for AccountType.None, which is, after all, what you defined in your POCO enum. This way you won't have to deal with a Nullable<AccountType> and your database maps better to your application.