2012-04-21 153 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