gpt4 book ai didi

c# - 具有常量的 Fluent NHibernate 引用

转载 作者:太空狗 更新时间:2023-10-30 01:20:36 30 4
gpt4 key购买 nike

我在 Fluent NHibernate 中映射了一个表。此表必须根据 ID 连接到另一个表,但还必须根据一组常量值过滤该表上的连接值。考虑以下 SQL:

SELECT * 
FROM
Table1
INNER JOIN
Table2 ON
Table1.Table2Id = Table2.Id
AND Table2.Category = 'A constant expression'
AND Table2.Language = 'A constant expression'

我对 Table1 的流畅映射目前看起来像这样:

References(a => a.Table2).Nullable().Columns("Table2Id").ReadOnly();

如何实现常量表达式?

最佳答案

听起来您可以使用过滤器来做到这一点。

首先,您需要定义过滤器类型

public class SpecificCategoryFilter : FilterDefinition
{
public SpecificCategoryFilter()
{
WithName("SpecificCategory").WithCondition("Category = 'A constant expression'");
}
}

public class SpecificLanguageFilter : FilterDefinition
{
public SpecificLanguageFilter()
{
WithName("SpecificLanguage").WithCondition("Language = 'A constant expression'");
}
}

已编辑:根据评论,没有 .ApplyFilter<TFilter>()References() ,所以更新了我认为使用过滤器的方法

需要在流式映射中应用过滤器

public class Table2Map : ClassMap<Table2>
{
public Table2Map()
{
// Other mappings here...

ApplyFilter<SpecificCategoryFilter>();
ApplyFilter<SpecificLanguageFilter>();
}
}

最后,当您打开 session 时,您需要启用过滤器

using (var session = sessionFactory.OpenSession())
{
session.EnableFilter("SpecificCategory");
session.EnableFilter("SpecificLanguage");
}

如果您正在使用 ICurrentSessionContext 的实现并且过滤器应始终适用,然后您可以在调用 ICurrentSessionContext.CurrentSession() 返回的 session 中启用过滤器.

现在,当查询 Table1 时, 为了激活 Table2 的过滤器,您需要指示 NHibernate 加入引用的 Table2 ;你可以使用

  1. Fetch(t => t.Table2).Eager
  2. JoinQueryOver(t => t.Table2) (以及类似的加入策略)

在不指示 NHibernate 进行连接的情况下,默认情况下将延迟加载引用,因此不会在查询中应用过滤器。缺点是Table2会很急切,但我不知道有什么方法可以应用过滤器。以下查询

session.QueryOver<Table1>().Inner.JoinQueryOver(t => t.Table2).List();

SQL 中的结果类似于

SELECT
this_.Id as Id0_1_,
this_.Table2Id as Table3_0_1_,
table2_.Id as Id1_0_,
table2_.Category as Category1_0_,
table2_.Language as Language1_0_
FROM
Table1 this_
inner join
Table2 table2_
on this_.Table2Id=table2_.Id
WHERE
table2_.Category = 'A constant expression'
and table2_.Language = 'A constant expression'

这类似于您在问题中使用的 SQL。

关于c# - 具有常量的 Fluent NHibernate 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18587615/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com