繁体   English   中英

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

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

给出下表:

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写入该列的数据库?”这样的内容?

将您的枚举声明为类中的可为空的属性/字段,以便默认值将为null。

例如:

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

如果您要坚持数据库中AccountStatus.None <=> NULL的概念,则应查看NHibernate IUserType接口。 使用此接口,您可以提供自定义逻辑,以将应用程序值来回转换为DB值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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