我有以下方法,目前它返回整个 sql 字符串。我将如何执行以下操作。
using (ITransaction transaction = session.BeginTransaction())
{
string sql =
string.Format(
@"DECLARE @Cost money
SET @Cost = -1
select @Cost = MAX(Cost) from item_costings
where Item_ID = {0}
and {1} >= Qty1 and {1} <= Qty2
RETURN (@Cost)",
itemId, quantity);
string mystring = session
.CreateSQLQuery(sql)
.ToString();
transaction.Commit();
return mystring;
}
Run Code Online (Sandbox Code Playgroud)
// 编辑
这是使用标准的最终版本
using (ISession session = NHibernateHelper.OpenSession())
{
decimal cost = session
.CreateCriteria(typeof (ItemCosting))
.SetProjection(Projections.Max("Cost"))
.Add(Restrictions.Eq("ItemId", itemId))
.Add(Restrictions.Le("Qty1", quantity))
.Add(Restrictions.Ge("Qty2", quantity))
.UniqueResult<decimal>();
return cost;
}
Run Code Online (Sandbox Code Playgroud)
NHibernate 仅支持从数据读取器读取结果。
您应该将查询字符串创建为:
string sql = string.Format(
@"select MAX(Cost) from item_costings
where Item_ID = {0}
and {1} >= Qty1 and {1} <= Qty2",
itemId, quantity);
Run Code Online (Sandbox Code Playgroud)
然后你用以下命令执行它:
string mystring = session
.CreateSQLQuery(sql)
.UniqueResult<decimal>()
.ToString();
Run Code Online (Sandbox Code Playgroud)
无论如何,您在这里根本没有使用 NHibernate 功能,您只是不必要地包装原始 ADO.NET。
为什么不定义一个对象模型并使用 Criteria、HQL 或 Linq 对其进行查询?