【问题标题】:How can I use the READPAST hint in NHibernate?如何在 NHibernate 中使用 READPAST 提示?
【发布时间】:2026-01-11 04:20:06
【问题描述】:

在从 SQL Server 选择数据时,有什么方法可以让 NHibernate 使用 the READPAST hint

【问题讨论】:

    标签: sql-server nhibernate query-hints


    【解决方案1】:

    选项 #1 简单方法:SQL 查询

    Session.CreateSQLQuery("select * from YourEntityTable with (readpast) where SomeColumn = :col")
    .AddEntity(typeof(YourEntity))
    .SetString("col", value)                            
    .UniqueResult<YourEntity>();
    

    选项 #2 需要更多工作:

    如果您没有使用 NHibernate.LockMode 之一,您可以将方言的 AppendLockHint() 覆盖为:

    public override string AppendLockHint(LockMode lockMode, string tableName)
    {
        if (lockMode == <lockModeYouWantToSacrificeForThis>)
        {
            return tableName + " with (readpast)";
        }
        return tableName;
    }
    

    【讨论】:

    • 或者您可以定义自己的 LockMode 枚举,其值与 NHibernate 的值相同,并添加一个具有显式值的枚举,然后在您的自定义方言中进行检查(将 NH LockMode 转换为您的)。这利用了 C# 枚举可以是任何值,而不仅仅是定义的值这一事实。