我有一个表结构:
------------------------------------------------
| id |daily_index|monthly_index| created |
------------------------------------------------
| GUID | 1 | 1 | 10-12-2014 |
| GUID | 2 | 2 | 10-12-2014 |
| GUID | 1 | 3 | 11-12-2014 |
| GUID | 1 | 1 | 01-01-2015 |
------------------------------------------------
我的目标是拥有一个具有灵活自然代码的交易对象,例如
INV-{daily_index}/{month_in_roman}/{year_in_roman}/{monthly_index}
或者
INV{ddmmyyyyhhiiss}-{monthly_index}-{daily_index}
或者用户希望的任何内容。
该类将有一个 Code
属性,该属性将编织这些私有(private)字段,仅用于 UI。
在纯 mysql 查询中,我会这样做:
INSERT INTO transaction VALUES (//Some GUID, (SELECT COUNT(*) + 1 FROM transaction WHERE DATE(created) = DATE(NOW)), (SELECT COUNT(*) + 1 FROM transaction WHERE MONTH (创建) = MONTH(NOW)), NOW());
我的问题是有没有办法在 NHibernate 中重现这种 INSERT 机制?
我考虑了另一种选择,我将使用 COUNT 查询进行 SELECT 查询,但我不知道 NHibernate 是否可行。
另一种选择是创建 MySQL 触发器,但我很想知道这是否可以直接在我的项目中执行。
最佳答案
NHibernate 提供了一个选项来覆盖默认的插入语句:sql-insert
:
在您的映射文件中使用此元素,您可以根据自己的喜好更改插入/更新语句,如下所示:
<class name="Student">
<id name="Id" type="Int32">
<generator class="assigned" />
</id>
<property name="Code" length="2000" />
<many-to-one name="Class" column="ClassId" not-null="true"/>
<sql-insert>insert into Student (Code, ClassId, Id) values (UPPER(?), ? , ?)</sql-insert>
</class>
当然,您还必须自定义 sql-update
。
不过,确定每一列的正确位置并不容易。这是来自 NH 文档:
You can see the expected order by enabling debug logging for the NHibernate.Persister.Entity level. With this level enabled NHibernate will print out the static SQL that is used to create, update, delete etc. entities. (To see the expected sequence, remember to not include your custom SQL in the mapping files as that will override the NHibernate generated static sql.)
关于c# - NHibernate 插入子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27426113/