我将 FluentnHibernate
用于我的数据层,并且我有一个主要通过nHibernate/LINQ
但在一些高级用法中填充的类,需要由存储过程填充。
我遇到的问题是类映射包含一个公式。当我调用一个nHibernate/LINQ
函数时,底层变量按预期填充;当我调用该GetNamedQuery()
函数时,它会引发错误:
值不能为空。参数名称:字段名
对于 aNamedQuery
来说,没有填充 Formula 字段是完全合乎逻辑的(显然我希望在这里有一个子查询,而不是为返回的每条记录运行 SQL 语句!),但我希望能够从存储过程——或者至少是查询不抛出错误。
这可能吗?
地图
public class QuoteMap : ClassMap<Quote>
{
public QuoteMap()
{
Id(x => x.Id).GeneratedBy.GuidComb();
...
Map(x => x.ResponseCount).Formula("(SELECT COUNT(*) FROM QuoteResponse WHERE QuoteResponse.QuoteId = Id and QuoteResponse.Status = " + (int)QuoteResponseRepository.Status.Live + ")");
}
}
存储库
// Works fine
public ICollection<Quote> GetAllByStatus(Status status)
{
using (ISession session = NHibernateHelper.OpenSession())
{
var quoteQuery = (from quote in session.Query<Quote>()
where quote.Status == (int)status
select quote).ToList();
return quoteQuery;
}
}
// Dies horribly
public ICollection<Quote> GetListPendingByCompany(Guid companyId, Status status)
{
using (ISession session = NHibernateHelper.OpenSession())
return session.GetNamedQuery("QuoteGetListPendingByCompany")
.SetGuid("Company_Id", companyId)
.SetInt32("QuoteStatus", (int)status)
.List<Quote>();
}
SQL
CREATE PROCEDURE [dbo].[QuoteGetListPendingByCompany]
@CompanyId uniqueidentifier,
@QuoteStatus int
AS
BEGIN
SET NOCOUNT ON;
SELECT
Quote.*,
(
SELECT
COUNT(*)
FROM QuoteResponse
WHERE QuoteResponse.QuoteId = Quote.Id
) AS ResponseCount -- Needs to populate what is currently a formula field
FROM Quote
-- ... code removed
END
StoredProcsMap.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="QMP.Data" namespace="QMP.Data.Model">
<sql-query name="QuoteGetListPendingByCompany" callable="true">
<return class="QMP.Data.Model.Quote, QMP.Data" />
<![CDATA[
exec dbo.QuoteGetListPendingByCompany @CompanyId=:Company_Id,@QuoteStatus=:QuoteStatus
]]>
</sql-query>
</hibernate-mapping>