2012-04-21 155 views
0

我有2個類,LogUserProfileLog有零個或一個對UserProfile的引用。NHibernate查詢相關表中的列

我想實現一個篩選器來搜索我的日誌。目前,它看起來像這樣:

/// <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 

我都想盡置換I能想到的得到這個工作,我不能。有人能告訴我我做錯了什麼嗎?

回答

1

我知道你說你已經嘗試過幾件事,但是你有沒有嘗試加入UserProfiles,使用致電CreateCriteria而不是SetFetchMode?也許像這樣:

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

爲了什麼目的?我試圖找回與UserProfile關聯的日誌記錄,而不是UserProfile記錄。 – 2012-04-21 22:49:39

+0

我知道你在日誌記錄之後而不是UserProfile記錄。你有沒有至少試過我的建議?我在使用Nhibernate時看到了同樣的錯誤,並且我認爲這與錯誤的連接有關。 – gowansg 2012-04-22 05:23:10

+0

這真的有竅門;我很抱歉懷疑你。 – 2012-04-22 13:50:14