简体   繁体   中英

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?"

Declare your enum as nullable property/field in class, so that the default value will be null.

For instance:

public class Entity 
{
  public int Id { get; set; }
  public AccountStatus? Status { get; set;}
}

If you want to stick to the conecpt of AccountStatus.None <=> NULL in the DB, then you should look at NHibernate IUserType interface. With this interface you can provide custom logic that converts application value to the DB value back and forth.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM