保存新实体时,NHibernate如何使用数据库默认值? [英] How can NHibernate use the database-default value when saving a new entity?
问题描述
考虑以下简单的C#类:
Consider the following simple C# class:
public class Entity
{
public Entity() { }
public virtual int Id { get; private set; }
public virtual DateTime DateCreated { get; private set; }
}
映射了以下简单的NHibernate映射:
Mapped with the following simple NHibernate mapping:
<class name="Entity" mutable="false">
<id name="Id">
<generator class="native">
</id>
<property name="DateCreated"/>
</class>
对于以下简单数据库模式:
To the following simple database schema:
CREATE TABLE Entity (
Id int IDENTITY(1,1) PRIMARY KEY,
DateCreated datetime NOT NULL DEFAULT getUtcDate()
)
在创建Entity
的新实例并将其保存到数据库时,如果NHibernate的值为null
,如何指示NHibernate将数据库的默认值用于DateCreated
列?或者,如何指定NHibernate在插入时应使用getUtcDate()
函数的结果作为DateCreated
字段的值?
When creating a new instance of the Entity
and saving to the database, how do you instruct NHibernate to use the database's default value for the DateCreated
column if its value is null
? Alternatively, how can I specify that NHibernate should use the result of the getUtcDate()
function as the value for the DateCreated
field upon insertion?
虽然我可以轻松添加
DateCreated = DateTime.Now;
使用实体服务器的本地时钟进入Entity构造函数,当有多个应用程序服务器(每个服务器可能具有不同步的本地时钟)时,我需要使用数据库的本地时钟来确保一致性.
into the Entity constructor, this is using the application server's local clock, and I need to use the database's local clock to ensure consistency when there are multiple application servers each with their potentially non-synchronized local clocks.
推荐答案
您可以指定该属性是由数据库生成的:
You can specify that the property is generated by the database:
因此,对于您的情况,您需要指定:
So for your case you would want to specify:
generated="insert"
通过这种方式,NHibernate知道在插入后必须刷新实体,但是更新后DateCreated将不会更改.
This way NHibernate knows after an INSERT it will have to refresh the entity, but after updates DateCreated will not be changed.
您可能还必须指定:
update="false" insert="false"
我从没使用过生成,而且我不确定NHibernate是否推断要设置这些,还是您必须显式地进行设置.
I've never used generated, and I'm not sure if NHibernate infers to set those or you have to do it explicitly.
这篇关于保存新实体时,NHibernate如何使用数据库默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!