0

: 我有一个问题... 我选择使用 NHibernate 3.3.3 源而不是预编译的 DLL 因为我厌倦了 NHibernate 问题并且无法调试它们(即黑匣子)。我对流利的 NHibernate 做了同样的事情。

我使用预编译的 NHibernate DLL 测试了我为流畅的 NHibernate 编译的源代码,它工作正常。所以我决定更进一步,对 NHibernate 做同样的事情。这就是糟糕的地方:我的应用程序启动,搜索引擎 vorks 等...但是每次我尝试保存某些内容时,我都会在 HqlTreeNodeExtensions 类(在文件 HQLTreeNode.cs 中)的“AsBooleanExpression”方法中收到 InvalidCastException “NHibernate.Hql.Ast.HQLBitWiseAnd”类型的值,无法将其转换为 NHibernate.Hql.Ast.HqlBooleanExpression。

为什么它适用于已编译的 DLL 而在源代码中不起作用?我对 NHibernate 的内部了解为零,对 c# 了解一点,因为我是一名 VB 开发人员。

这就是它发生的地方:

public static class HqlTreeNodeExtensions
{
    public static HqlExpression AsExpression(this HqlTreeNode node)
    {
        // TODO - nice error handling if cast fails
        return (HqlExpression)node;
    }

    public static HqlBooleanExpression AsBooleanExpression(this HqlTreeNode node)
    {
        if (node is HqlDot)
        {
            return new HqlBooleanDot(node.Factory, (HqlDot) node);
        }


        // TODO - nice error handling if cast fails
        return (HqlBooleanExpression)node;  <-------- RIGHT HERE - the cast fails      
    }
}

(无法为堆栈调用发布图像;将尝试将其转换为 readavle 文本)

有人可以帮助他吗?

非常感谢

尼科

PS这是完整的调用堆栈:好的;在这里我们获取完整的调用堆栈:摘自我自己的代码:一切都从“Dim ctrlResultatsRecherche As New ResultatsRechercheClientV2 ...”行开始

    Private Sub RechercheClient_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles txtCodePostal.KeyDown, txtClient.KeyDown, txtRue.KeyDown, txtVille.KeyDown
        If e.KeyCode = Keys.Enter Then

            Dim bolMaibecExpress As Boolean = False

            'Récupérer le contrôle parent.
            If Not Parent Is Nothing AndAlso TypeOf Parent.Parent Is SaisieDemandeEchantillon Then
                bolMaibecExpress = TryCast(Parent.Parent, SaisieDemandeEchantillon).chkMaibecExpress.Checked
            End If

            panDetails.Controls.DisposeAndRemoveAll()
            Dim ctrlResultatsRecherche As New ResultatsRechercheClientV2(m_Session, txtClient.Text, txtCodePostal.Text, txtVille.Text, txtRue.Text, bolMaibecExpress) 
            AddHandler ctrlResultatsRecherche.ClientSelectionneV2, AddressOf RésultatsRecherche_ClientSélectionné
            panDetails.Controls.Add(ctrlResultatsRecherche)
            panDetails.Visible = True
        End If
    End Sub

然后摘自我自己的代码:停在“Dim resultats = m_Session.Query(Of Client).Where(predicat.Expand).ToList”行

Public Sub New(ByVal session As ISession, ByVal strClient As String, ByVal strCodePostal As String, ByVal strVille As String, ByVal strRue As String, Optional ByVal MaibecExpress As Boolean = False)

    ' This call is required by the Windows Form Designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    dgvResultatsRecherche.AutoGenerateColumns = False

    m_Session = session

    Dim predicat = PredicateBuilder.False(Of Client)()
    predicat = predicat.Or(Function(x As Client) (x.Prenom.Contains(strClient) OrElse x.Nom.Contains(strClient) OrElse x.Telephone.Contains(strClient) OrElse x.Courriel.Contains(strClient) OrElse strClient = "") _
                                                And (x.Adresse.CodePostal.Contains(strCodePostal) Or strCodePostal = "") _
                                                And (x.Adresse.Ville.Contains(strVille) Or strVille = "") _
                                                And (x.Adresse.Ligne1.Contains(strRue) Or strRue = "") _
                                                And (x.MaibecExpress = MaibecExpress Or MaibecExpress = False))

    Dim resultats = m_Session.Query(Of Client).Where(predicat.Expand).ToList
    dgvResultatsRecherche.DataSource = resultats
    lblNbResultatsTrouvés.Text = String.Format("{0} résultats trouvés", resultats.Count)
    SetDataBindings()
End Sub

然后调用 remotion.link.dll -> Remotion.Linq.QueryableBase.GetEnumerator() (对不起,没有代码)

然后在“NhLinqExpression nhLinqExpression = PrepareQuery(expression, out query, out nhQuery);”处从 NHibernate.Linq.DefaultQueryProvider 执行 sub 线

    public TResult Execute<TResult>(Expression expression)
    {
        return (TResult) Execute(expression);
    }

然后在“return”行从 NHibernate.Linq.DefaultQueryProvider 执行 sub

    public virtual object Execute(Expression expression)
    {
        IQuery query;
        NhLinqExpression nhQuery;
        NhLinqExpression nhLinqExpression = PrepareQuery(expression, out query, out nhQuery);

        return ExecuteQuery(nhLinqExpression, query, nhQuery);
    }

然后在“query = Session.CreateQuery(nhLinqExpression);”处来自 NHibernate.Linq.DefaultQueryProvider 的 PrepareQuery 线

    protected NhLinqExpression PrepareQuery(Expression expression, out IQuery query, out NhLinqExpression nhQuery)
    {
        var nhLinqExpression = new NhLinqExpression(expression, Session.Factory);

        query = Session.CreateQuery(nhLinqExpression);

        nhQuery = query.As<ExpressionQueryImpl>().QueryExpression.As<NhLinqExpression>();

        SetParameters(query, nhLinqExpression.ParameterValuesByName);
        SetResultTransformerAndAdditionalCriteria(query, nhQuery, nhLinqExpression.ParameterValuesByName);
        return nhLinqExpression;
    }

然后从 NHibernate.Impl.AbstractSessionImpl CreateQuery sub,在“var queryPlan = GetHQLQueryPlan(queryExpression, false);” 线

    public virtual IQuery CreateQuery(IQueryExpression queryExpression)
    {
        using (new SessionIdLoggingContext(SessionId))
        {
            CheckAndUpdateSessionStatus();
            var queryPlan = GetHQLQueryPlan(queryExpression, false);
            var query = new ExpressionQueryImpl(queryPlan.QueryExpression, 
                                            this,
                                            queryPlan.ParameterMetadata
                                            );
            query.SetComment("[expression]");
            return query;
        }
    }

然后是 NHibernate.Impl.AbstractSessionImpl 中的 GetHQLQueryPlan 子程序(在返回线卡住)

    protected internal virtual IQueryExpressionPlan GetHQLQueryPlan(IQueryExpression queryExpression, bool shallow)
    {
        using (new SessionIdLoggingContext(SessionId))
        {
            return factory.QueryPlanCache.GetHQLQueryPlan(queryExpression, shallow, EnabledFilters);
        }
    }

然后从 NHibernate.Engine.Query.QueryPlan 中获取 GetHQLQueryPlan 子(线路计划中的堵塞 = new HQLExpressionQueryPlan (...))

    public IQueryExpressionPlan GetHQLQueryPlan(IQueryExpression queryExpression, bool shallow, IDictionary<string, IFilter> enabledFilters)
    {
        string expressionStr = queryExpression.Key;

        var key = new HQLQueryPlanKey(queryExpression, shallow, enabledFilters);
        var plan = (IQueryExpressionPlan)planCache[key];

        if (plan == null)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("unable to locate HQL query plan in cache; generating (" + expressionStr + ")");
            }
            plan = new HQLExpressionQueryPlan(expressionStr, queryExpression, shallow, enabledFilters, factory);
            planCache.Put(key, plan);
        }
        else
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("located HQL query plan in cache (" + expressionStr + ")");
            }
            var planExpression = plan.QueryExpression as NhLinqExpression;
            var expression = queryExpression as NhLinqExpression;
            if (planExpression != null && expression != null)
            {
                //NH-3413
                //Here we have to use original expression.
                //In most cases NH do not translate expression in second time, but 
                // for cases when we have list parameters in query, like @p1.Contains(...),
                // it does, and then it uses parameters from first try. 
                //TODO: cache only required parts of QueryExpression
                planExpression._expression = expression._expression;
                planExpression._constantToParameterMap = expression._constantToParameterMap;
            }
        }

        return plan;
    }

然后在 HQLExpressionQueryPlan 中(跳过属性),在返回行:

    private static IQueryTranslator[] CreateTranslators(string expressionStr, IQueryExpression queryExpression, string collectionRole, bool shallow, IDictionary<string, IFilter> enabledFilters, ISessionFactoryImplementor factory)
    {
        IQueryTranslatorFactory2 qtFactory = new ASTQueryTranslatorFactory();

        return qtFactory.CreateQueryTranslators(expressionStr, queryExpression, collectionRole, shallow, enabledFilters, factory);
    }

然后在 ASTQueryTranslatorFactory.cs 中的返回行:

    public IQueryTranslator[] CreateQueryTranslators(string queryIdentifier, IQueryExpression queryExpression, string collectionRole, bool shallow, IDictionary<string, IFilter> filters, ISessionFactoryImplementor factory)
    {
        return CreateQueryTranslators(queryExpression.Translate(factory), queryIdentifier, collectionRole, shallow,
                                      filters, factory);
    }

在 QueryModelVisitor.cs 中,在 GenerateHqlQuery(仅摘录)中的 Visitor.Visit() 行 //... // 识别和命名查询源 QuerySourceIdentifier.Visit(parameters.QuerySourceNamer, queryModel);

        var visitor = new QueryModelVisitor(parameters, root, queryModel) { RewrittenOperatorResult = result };
        visitor.Visit();

        return visitor._hqlTree.GetTranslation();

然后对我没有代码的 Remotion DLL 进行了几次调用......然后,在 QueryModelVisitor.cs 中,在 VisitWhereClause 中,在行 var expression =...

    public override void VisitWhereClause(WhereClause whereClause, QueryModel queryModel, int index)
    {
        // Visit the predicate to build the query
        var expression = HqlGeneratorExpressionTreeVisitor.Visit(whereClause.Predicate, VisitorParameters).AsBooleanExpression();
        if (whereClause is NhHavingClause)
        {
            _hqlTree.AddHavingClause(expression);
        }
        else
        {
            _hqlTree.AddWhereClause(expression);
        }
    }

然后在 HQLGeneratorExpressionTreeVisitor.cs 中,在访问函数中,行返回:

    public static HqlTreeNode Visit(Expression expression, VisitorParameters parameters)
    {
        return new HqlGeneratorExpressionTreeVisitor(parameters).VisitExpression(expression);
    }

然后,在同一个文件中,行 return VisitBinaryExpression((BinaryExpression) expression) - (仅摘录):

            //...
            case ExpressionType.GreaterThan:
            case ExpressionType.LessThan:
            case ExpressionType.LessThanOrEqual:
            case ExpressionType.Coalesce:
            case ExpressionType.ArrayIndex:
                return VisitBinaryExpression((BinaryExpression) expression);
            case ExpressionType.Conditional:
                return VisitConditionalExpression((ConditionalExpression) expression);
            case ExpressionType.Constant:
                return VisitConstantExpression((ConstantExpression) expression);
            //...

相同的文件,函数 VisitBinaryExpression,linereturn _hqlTreeBuilder.BooleanOr(lhs.AsBooleanExpression(), rhs.AsBooleanExpression()) - 仅摘录

            //...
            case ExpressionType.AndAlso:
                return _hqlTreeBuilder.BooleanAnd(lhs.AsBooleanExpression(), rhs.AsBooleanExpression());

            case ExpressionType.Or:
                return _hqlTreeBuilder.BitwiseOr(lhs, rhs);

            case ExpressionType.OrElse:
                return _hqlTreeBuilder.BooleanOr(lhs.AsBooleanExpression(), rhs.AsBooleanExpression());

            case ExpressionType.Add:
                if (expression.Left.Type == typeof (string) && expression.Right.Type == typeof (string))
                {
                    return _hqlTreeBuilder.MethodCall("concat", lhs, rhs);
                }
                return _hqlTreeBuilder.Add(lhs, rhs);       
            //...

最后,在 HQLTreeNode.cs 中,行 return (HqlBooleanExpression)node ,靠近奇怪的待办事项注释:

public static class HqlTreeNodeExtensions
{
    public static HqlExpression AsExpression(this HqlTreeNode node)
    {
        // TODO - nice error handling if cast fails
        return (HqlExpression)node;
    }

    public static HqlBooleanExpression AsBooleanExpression(this HqlTreeNode node)
    {
        if (node is HqlDot)
        {
            return new HqlBooleanDot(node.Factory, (HqlDot) node);
        }

        // TODO - nice error handling if cast fails
        return (HqlBooleanExpression)node;
    }
}               
4

1 回答 1

1

您可能正在中断抛出的异常,但如果您继续 (F5),则该异常将在 NHibernate 源代码中的更高级别进行处理。虽然源代码中的注释让我怀疑。试试这个:在 Visual Studio 中,转到“调试”>“异常”并取消选中“抛出的公共语言运行时异常”列中的复选框。

于 2013-05-01T18:35:53.840 回答