如何使用NHibernate为枚举设置默认值?

时间:2013-01-17 17:26:06

标签: c# .net nhibernate nhibernate-mapping

鉴于以下表格:

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
)

并给出以下枚举定义:

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

当我创建Account对象时,如果我保留AccountType的默认AccountType.None值,那么在写入数据库时​​它会尝试插入0(这会使感觉)但由于我们对表有外键限制,因此抛出异常。我们需要插入null或引用表中存在的值。

我的问题是:NHibernate是否可以说“如果我的枚举没有设置,那么将null写入该列的数据库?”

2 个答案:

答案 0 :(得分:3)

在类中声明你的枚举为可为空的属性/字段,因此默认值为null。

例如:

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

如果你想坚持使用AccountStatus.None< =>的conecpt在DB中为NULL,那么你应该看看NHibernate的IUserType接口。使用此接口,您可以提供自定义逻辑,将应用程序值来回转换为DB值。

答案 1 :(得分:0)

您可以为AccountType表添加相应的值,AccountType.None,这毕竟是您在POCO枚举中定义的值。这样您就不必处理Nullable<AccountType>,并且您的数据库可以更好地映射到您的应用程序。

相关问题