Tha's what I like on NHibernate ... even here is a solution. What we would need is the:
Small cite:
As already discussed, automatic and transparent object/relational mapping is concerned with the management of object state. This implies that the object state is available in memory, hence manipulating (using the SQL Data Manipulation Language (DML) statements: INSERT, UPDATE, DELETE) data directly in the database will not affect in-memory state. However, NHibernate provides methods for bulk SQL-style DML statement execution which are performed through the Hibernate Query Language (HQL).
About INSERT (small extract):
The pseudo-syntax for INSERT statements is: INSERT INTO EntityName properties_list select_statement. Some points to note:
- Only the INSERT INTO ... SELECT ... form is supported; not the INSERT INTO ... VALUES ... form.
- The properties_list is analogous to the column speficiation in the SQL INSERT statement. For entities involved in mapped inheritence, only properties directly defined on that given class-level can be used in the properties_list. Superclass properties are not allowed; and subclass properties do not make sense. In other words, INSERT statements are inherently non-polymorphic.
- ...
example from doc:
ISession session = sessionFactory.OpenSession();
ITransaction tx = session.BeginTransaction();
var hqlInsert = "insert into DelinquentAccount (id, name) " +
" select c.id, c.name from Customer c where ...";
int createdEntities = s.CreateQuery( hqlInsert )
.ExecuteUpdate();
tx.Commit();
session.Close();
SOLUTION
having this we can create kind of this select:
var hqlSelect =
// HQL select clause
" SELECT " +
// guid on the DB side
" UUID(), " +
// this will return matches for today only
" CAST(SUM(CASE WHEN DAY(created)=DAY(CURRENT_TIMESTAMP) THEN 1 ELSE 0 END) as int),"+
// this will return matches for this month - see WHERE
" CAST(Count(*) as int)," +
// the time stamp into created
" CAST(CURRENT_TIMESTAMP as DateTime)" +
// From means - from some entity (the transaction here)
" FROM transaction" +
// Where is here restricting current month
// here we filter just this year and this month records
" WHERE MONTH(created) = MONTH(CURRENT_TIMESTAMP) " +
" AND YEAR(created) = YEAR(CURRENT_TIMESTAMP) ";
And this would be the COMPLETE insert
var hqlInsert = "INSERT INTO AuditLog (id, daily_index, monthly_index, created ) "
+ hqlSelect; // the above select
And this should do what expected:
ISession session = sessionFactory.OpenSession();
ITransaction tx = session.BeginTransaction();
var hqlInsert = ... // see code above to create DML HQL
int createdEntities = session
.CreateQuery( hqlInsert )
.ExecuteUpdate();
tx.Commit();
session.Close();