NHibernate Notes3_How to set a default value of column
2011-09-25 22:50 小郝(Kaibo Hao) 阅读(1944) 评论(0) 编辑 收藏 举报To set a default value of column we need to take the advantage of setting the default value of the column within the native DB. In NHibernate we should the set the attritute "generated" to be "alway" or "insert" which will tell NHibernate to fullfill the value of the column with the value assigned from the native DB. Actually there are three value options for the "generated" attribute.
As it described in "NHibernate Reference Documentation". They are:
1. never (the default) - means that the given property value is not generated within the database.
2. insert - states that the given property value is generated on insert, but is not regenerated on subsequent updates. Things like created-date would fall into this category. Note that even though Section 5.1.7, “version (optional)” and Section 5.1.8, “timestamp (optional)” properties can be marked as generated, this option is not available there...
3. always - states that the property value is generated both on insert and on update.
And there is some sample code to illerstrate how to use it:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="EasyNH.Model" namespace="EasyNH.Model">
<class name="Product">
<id name="Id">
<generator class="guid.comb" />
</id>
<property name="Name" not-null="true" />
<property name="Description" />
<property name="UnitPrice" not-null="true" type="Currency" />
<property name="ServerTime" generated="always" type="DateTime" ></property>
</class>
</hibernate-mapping>
This is very useful when we want to set column value at the DB side. For example, if you want to set the update/insert time as precise service DB server time of a record in a table, you can set the column default value as "getdate()", and then set configuration described above in NHibernate.
And you can download my sample project from the link below. You can run the Unit Test to build the Test DB with method "Can_generate_schema" and test it with method "AddOrderTest" in "TestNH" project. You can only prove the dafault funciton with running it with Product entity but not others, because I did not finish that mapping whole correctly yet. Just enjoy it! :)
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。