问题
Does anyone know how to express the following SQL statement using NHibernate criteria?
SELECT SUM(Val1 + Val2) FROM SomeTable
Seems simple, but AFAIK I can't seem to find a way to do this without returning an array of values, the sums of Val1 + Val2 seperately and then summing from the array, which I want to avoid.
回答1:
In comments to blog post that @Jaguar has mentioned in his answer NHibernate and the missing OperatorProjection is an alternative solution:
session.CreateCriteria().SetProjection(
Projections.Property<SomeType>(val => val.Id),
Projections.Property<SomeType>(val => val.Duration),
Projections.SqlFunction(
new VarArgsSQLFunction("(", "+", ")"),
NHibernateUtil.Double,
Projections.Property<SomeType>(val => val.Duration),
Projections.Constant(1)
)
).List();
All credit goes to Tomek.
This might look sth like:
Projections.Sum(
Projections.SqlFunction(
new VarArgsSQLFunction("(", "+", ")"),
NHibernateUtil.Int32,
Projections.Property<SomeTableType>(val => val.Val1),
Projections.Property<SomeTableType>(val => val.Val2)
)
)
Especially VarArgsSQLFunction is useful.
回答2:
Well, after reading for the n-th time a question with this exact problem i decided to write an implementation that doesn't include writing SQL.
You can check the implementation at http://savale.blogspot.com/2011/04/nhibernate-and-missing.html with which you can write:
criteria.SetProjection(
new ArithmeticOperatorProjection("+",
NHibernateUtil.Int32,
Projections.Property("Prop1"), Projections.Property("Prop2")
)
);
回答3:
I guess that Val1 and Val2 are property values from your entities. It that case you can write your own custom NHibernate.Criterion.ICriterion. In your case you will just implement methods ToSqlString.
回答4:
or you can use HQL to achieve the same. it lets you operate on your .net objects and then queries the server accordingly..
you can build up your query as follows
var hqlQuery= string.format(" select a.prop1 + a.prop2 from ClassA as a where a.Id={0}",val);
return session.CreateQuery(hqlQuery).UniqueResult<double>();
来源:https://stackoverflow.com/questions/4627425/using-nhibernate-criteria-to-sum-across-multiple-properties-columns