NHibernate查询相关表中的列

时间:2012-04-21 19:53:39

标签: c# nhibernate

我有2个课程,LogUserProfileLogUserProfile的引用为零或一个。

我正在尝试实现一个用于搜索日志的过滤器。目前它看起来像这样:

    /// <summary>
    /// Searches the logs for matching records
    /// </summary>
    /// <param name="fromUTC">Start point timestamp of the search</param>
    /// <param name="toUTC">End point timestamp of the search</param>
    /// <param name="ofSeverity">Severity level of the log entry</param>
    /// <param name="orHigher">Retrieve more severe log entries as well that match</param>
    /// <param name="sourceStartsWith">The source field starts with these characters</param>
    /// <param name="usernameStartsWith">The username field starts with these characters</param>
    /// <param name="maxRecords">The maximum number of records to return</param>
    /// <returns>A list of Log objects with attached UserProfile objects</returns>
    public IEnumerable<Log> SearchLogs(
        DateTime fromUTC,
        DateTime toUTC,
        string ofSeverity,
        bool orHigher,
        string sourceStartsWith,
        string usernameStartsWith,
        int maxRecords)
    {
        ofSeverity = ofSeverity ?? "INFO";

        var query = DetachedCriteria.For<Log>()
            .SetFetchMode("UserProfile", NHibernate.FetchMode.Eager)
            .Add(Restrictions.In("Severity", (orHigher ?
                Translator.SeverityOrHigher(ofSeverity) : Translator.Severity(ofSeverity)).ToArray()))
            .Add(Restrictions.Between("TimeStamp", fromUTC, toUTC))
            .AddOrder(Order.Desc("TimeStamp"))
            .SetMaxResults(maxRecords);

        if ((sourceStartsWith ?? string.Empty).Length > 0)
        {
            query
                .Add(Restrictions.InsensitiveLike("Source", sourceStartsWith, MatchMode.Start));
        }

        if ((usernameStartsWith ?? string.Empty).Length > 0)
        {
            query
                .Add(Restrictions.InsensitiveLike("UserProfile.UserName",
                    usernameStartsWith, MatchMode.Start));
        }

        return query.GetExecutableCriteria(_Session).List<Log>();
    }

...只要我没有指定usernameStartsWith值,这就可以正常工作。

如果我指定usernameStartsWith值,我会看到一个可爱的黄色死亡屏幕:

could not resolve property: UserProfile.UserName of: C3.DataModel.Log

我已经尝试过每一种我能想到的排列方式来实现这一点,而我却做不到。有人能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

我知道你说过你已经尝试了一些事情,但是你是否尝试过使用CreateCriteria而不是SetFetchMode来加入UserProfiles?也许是这样的:

    if ((usernameStartsWith ?? string.Empty).Length > 0)
    {
        query.CreateCriteria("UserProfile")
             .Add(Restrictions.InsensitiveLike("UserName",
                usernameStartsWith, MatchMode.Start));
    }