【问题标题】:Joining two unrelated view-tables with nhibernate and ICriteria使用 nhibernate 和 ICriteria 连接两个不相关的视图表
【发布时间】:2014-10-13 07:52:42
【问题描述】:

我有两个基于两个视图的实体。映射如下所示:

实体 A:

<class name="SearchView" table="SearchView" dynamic-update="true" mutable="false" schema-action="none">
    <id name="Id" type="Guid" column="Id" />
    <property name="Id" column="Id" type="Guid" />
    <property name="Expires" column="Expires" type="DateTime" />
    <property name="VerificationNumber" column="VerificationNumber" type="Int32" />
    <property name="InvoiceNo" column="InvoiceNo" type="Int32" length="50" />
    <property name="Status" column="FakturaStatus" type="Int32" />
</class>

实体 B:

<class name="SearchInvoiceResourceLookUpView" table="SearchInvoiceResourceLookUpView" dynamic-update="true" mutable="false" schema-action="none">
    <id name="Id" type="Guid" column="Id" />

    <property name="InvoiceId" column="InvoiceId" type="Guid" />
    <property name="ResourceId" column="ResourceId" type="Guid" />        
</class>

实体 A 基于表视图,该表视图是更复杂表结构的平面视图,用于搜索优化。现在我希望能够从 Entity A 中获取所有行,其中 ID 位于 Entity B 中的“InvoiceId”列中,以获取 Entity B 中“ResourceId”的特定值strong>Entity B 使用 NHibernate 和 Criteria-API。这两个表都是视图,它们没有声明的关系。我在 C# 中尝试过以下代码,但它不起作用:

        var criteria = _session.CreateCriteria(typeof(SearchView));
            criteria.CreateAlias("SearchInvoiceResourceLookUpView", "srf",JoinType.InnerJoin)
                .Add(Restrictions.EqProperty("sfr.InvoiceId", "Id"))
                .Add(Restrictions.Eq("sfr.ResourceId", invoiceResId));

用于此目的的原始 SQL 将是:

SELECT * FROM SearchView
JOIN SearchInvoiceResourceLookUpView srf on srf.InvoiceId = Id 
WHERE srf.ResourceId = '[Inser resource id here]'

我该如何解决?

还有其他更好的方法吗?

【问题讨论】:

    标签: c# sql .net nhibernate icriteria


    【解决方案1】:

    在我们的实体之间没有显式映射的情况下,我们可以仅使用 HQL。

    可能会出现多个类,从而导致笛卡尔积或“交叉”连接。

    from Formula, Parameter
    from Formula as form, Parameter as param
    

    所以在上面的例子中,我们会有这样的 HQL:

    FROM SearchView AS sv, SearchInvoiceResourceLookUpView AS srf
    WHERE srf.InvoiceId = sv.Id
    AND srf.ResourceId = '[Inser resource id here]'
    

    还应该使用一些 SELECT 并且可能使用带有 Result Transformer 的 DTO...

    【讨论】:

    • 感谢您的回答。我想这也可以用 Linq 来完成?
    • 不能说 NHibernate 的 Linq 提供程序...我会说它现在正在使用 HQL,所以也许...但真的不确定... ;( 我的偏好是 Criteria 或 QueryOver甚至 HQL...
    • 我会尝试两者。根据搜索时提供的参数,还需要在查询中包含或不包含参数。
    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 2010-10-09
    • 2017-09-28
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多