2012-04-21 3 views
0

У меня есть два объекта POCO как таковые:комплекс NHibernate запрос ... за пределами моего понимания

///<summary> 
///Auto-generated concrete POCO for persistance use <strong>Log</strong> 
///</summary> 
public class Log : ILogExtended 
{ 
    #region Primitive Properties 

    ///<summary> 
    /// The log entry ID 
    ///</summary> 
    public virtual int LogId { get; set; } 

    ///<summary> 
    /// The timestamp of the log entry (UTC) 
    ///</summary> 
    public virtual DateTime TimeStamp { get; set; } 

    ///<summary> 
    /// The thread ID that generated the log entry 
    ///</summary> 
    public virtual string Thread { get; set; } 

    ///<summary> 
    /// The severity of the log entry 
    ///</summary> 
    public virtual string Severity { get; set; } 

    ///<summary> 
    /// The source module of the log entry 
    ///</summary> 
    public virtual string Source { get; set; } 

    ///<summary> 
    /// The log entry message 
    ///</summary> 
    public virtual string Message { get; set; } 

    ///<summary> 
    /// The associated exception text associated with the log entry 
    ///</summary> 
    public virtual string Exception { get; set; } 
    #endregion 

    #region Navigation Properties 

    ///<summary> 
    /// The user associated with the log entry 
    ///</summary> 
    public virtual UserProfile UserProfile { get; set; } 
    #endregion 

    #region Navigation Collections 
    #endregion 
} 

и

///<summary> 
///Auto-generated concrete POCO for persistance use <strong>UserProfile</strong> 
///</summary> 
public class UserProfile : IUserProfileExtended 
{ 
    #region Primitive Properties 

    ///<summary> 
    /// The unique ID of the profile 
    ///</summary> 
    public virtual int UserID { get; set; } 

    ///<summary> 
    /// The given name of the profile 
    ///</summary> 
    public virtual string GivenName { get; set; } 

    ///<summary> 
    /// The middle name of the profile 
    ///</summary> 
    public virtual string MiddleName { get; set; } 

    ///<summary> 
    /// The family name of the profile 
    ///</summary> 
    public virtual string FamilyName { get; set; } 

    ///<summary> 
    /// The user name of the profile 
    ///</summary> 
    public virtual string UserName { get; set; } 

    ///<summary> 
    /// The nickname of the profile 
    ///</summary> 
    public virtual string NickName { get; set; } 

    ///<summary> 
    /// The first address line of the profile 
    ///</summary> 
    public virtual string Address1 { get; set; } 

    ///<summary> 
    /// The second address line of the profile 
    ///</summary> 
    public virtual string Address2 { get; set; } 

    ///<summary> 
    /// The mailing address city of the profile 
    ///</summary> 
    public virtual string City { get; set; } 

    ///<summary> 
    /// The mailing address state of the profile 
    ///</summary> 
    public virtual string State { get; set; } 

    ///<summary> 
    /// The mailing address zip code of the profile 
    ///</summary> 
    public virtual string ZipCode { get; set; } 

    ///<summary> 
    /// The user's self description 
    ///</summary> 
    public virtual string Bio { get; set; } 

    ///<summary> 
    /// The user's birth date. 
    ///</summary> 
    public virtual Nullable<DateTime> BirthDate { get; set; } 

    ///<summary> 
    /// The user's photo URL 
    ///</summary> 
    public virtual string LinkToAvatar { get; set; } 

    ///<summary> 
    /// The user's website URL 
    ///</summary> 
    public virtual string LinkToWebpage { get; set; } 
    #endregion 

    #region Navigation Properties 
    #endregion 

    #region Navigation Collections 

    ///<summary> 
    /// The log entries of the user's actions 
    ///</summary> 
    public virtual IList<Log> ActivityLogs { get; set; } 
    #endregion 
} 

Эти объекты сопоставляются в базе данных следующим образом:

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        assembly="C3.DataModel.Generated" 
        namespace="C3.DataModel"> 
    <class name="Log" table="Logs"> 
     <id name="LogId"> 
      <generator class="identity" /> 
     </id> 
     <property name="TimeStamp" column="TimeStamp" index="ixLogTimeStamp" not-null="true" /> 
     <property name="Thread" length="255" column="Thread" not-null="true" /> 
     <property name="Severity" column="Severity" not-null="true" /> 
     <property name="Source" length="255" not-null="false" column="Source" /> 
     <property name="Message" length="4000" not-null="true" column="Message"/> 
     <property name="Exception" length="4000" column="Exception"/> 
     <many-to-one name="UserProfile" column="UserID" cascade="none" not-found="ignore"/> 
    </class> 
</hibernate-mapping> 

и

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        assembly="C3.DataModel.Generated" 
        namespace="C3.DataModel"> 
    <class name="UserProfile" table="UserProfiles"> 
     <id name="UserID"> 
      <generator class="assigned" /> 
     </id> 
     <property name="GivenName" length="40" column="GivenName" /> 
     <property name="MiddleName" length="40" column="MiddleName" not-null="false" /> 
     <property name="FamilyName" length="40" column="FamilyName" /> 
     <property name="UserName" length="250" index="ixUserName" unique="true" /> 
     <property name="NickName" length="40" column="NickName" /> 
     <property name="Address1" length="50" column="Address1" /> 
     <property name="Address2" length="50" column="Address2" /> 
     <property name="City" length="50" column="City" /> 
     <property name="State" length="2" column="State" /> 
     <property name="ZipCode" length="10" column="ZipCode" /> 
     <property name="Bio" length="2000" column="Bio" not-null="false" /> 
     <property name="BirthDate" not-null="false" column="BirthDate" /> 
     <property name="LinkToAvatar" length="250" column="LinkToAvatar" not-null="false" /> 
     <property name="LinkToWebpage" length="250" column="LinkToWebPage" not-null="false" /> 
    </class> 
</hibernate-mapping> 

Я пытаюсь построить функцию Log Searcher как таковой:

/// <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 nuber 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) 
    { 
     var result = _Session 
      (SOMETHING goes here) 
    } 

Как n00b в NHibernate, такого рода многогранный запрос получил меня чесать голову, и я оценил бы некоторую помощь. Если вы можете четко указать, как я буду изменять заявления для других подобных запросов, я был бы очень благодарен.

Одно примечание: Уровень серьезности будет IEnumerable<string>, одного или нескольких значений, если установлен параметр orHigher.

Спасибо за внимание.

+0

Таким образом, в (КОЕ идет здесь) часть. Это будет то, где вы пишете свой nhibernate-запрос. Вы можете использовать API критериев или Queryover. – CrazyCoderz

+0

После того, как вы попытаетесь написать запрос, если у вас есть проблема, отправьте код для запроса, и мы поможем вам. PS .. Запросы получают больше удовольствия – CrazyCoderz

+0

Хорошая отправная точка для вас. http://nhforge.org/blogs/nhibernate/archive/2009/12/17/queryover-in-nh-3-0.aspx – CrazyCoderz

ответ

0

Вот что я закончил с, не стесняйтесь сказать мне, если я делаю что-то неправильно или нерационально:

/// <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 (!string.IsNullOrEmpty(usernameStartsWith)) 
     { 
      query.CreateCriteria("UserProfile") 
       .Add(Restrictions.InsensitiveLike("UserName", 
       usernameStartsWith, MatchMode.Start)); 
     } 

     if (!string.IsNullOrEmpty(sourceStartsWith)) 
     { 
      query 
       .Add(Restrictions.InsensitiveLike("Source", sourceStartsWith, MatchMode.Start)); 
     } 

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

    }