c# - NHibernate 插入子查询

标签 c# mysql .net nhibernate insert

我有一个表结构:

------------------------------------------------
|  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.)

引用: Custom SQL for create, update and delete

关于c# - NHibernate 插入子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27426113/

相关文章:

c# - 按条件点击表单

c# - 将 Listview 项目计数绑定(bind)到 Xamarin Forms 中的标签可见性

c# - 在安装时设置 .NET Windows 服务的角色...从 app.config 设置

c# - 为什么我的 MenuStrip 在第一次点击时出现在错误的位置?

php - (PHP) 具有排序依据和一定范围的 MySQL 随机行大表

mysql - 如何在客户在线下订单时处理数据库中的价格变化?

php - foreach($q->result() as $row) 在结果集中循环两次

c# - 使用 Youtube .net API 上传视频并将其设置为不公开

c# - 如何在 C# 中读取带有 .net 4 的 IIS7 上的 web.config 的一部分

c# - 如何使用 AutoMapper 映射子对象?