2010-07-27 26 views
2

我擺弄我的存儲庫類,並試圖執行一個分離標準的查詢。但是,它似乎並不喜歡我將結果轉換器設置爲非AR類型。使用DetachedCriteria返回非AR類型的通用列表

public class IncidentRepository 
{ 
    public static IList<AuditReport> GetAllIncidentsToAudit() 
    { 
     DetachedCriteria dc = DetachedCriteria.For<Incident>("i") 
      .SetProjection(
       Projections.ProjectionList() 
        .Add(Projections.Property("i.Id"), "IncidentId") 
        .Add(Projections.Property("l.Id"), "LocationId") 
      ) 
      .CreateCriteria("Locations", "l") 
       .Add(Expression.Eq("l.PrimaryLocationFlag", "T")) 
      .SetResultTransformer(Transformers.AliasToBean<AuditReport>()); 

     return ActiveRecordMediator<AuditReport>.FindAll(dc); 
    } 
} 

public class AuditReport 
{ 
    public int IncidentId { get; set; } 
    public int LocationId { get; set; } 
} 

執行這個查詢時,我得到的錯誤是:

You have accessed an ActiveRecord class that wasn't properly initialized. There are two possible explanations: that the call to ActiveRecordStarter.Initialize() didn't include castle.AuditReport class, or that castle.AuditReport class is not decorated with the [ActiveRecord] attribute. 

我理解的錯誤,但我怎麼能返回非AR型的強類型列表?我已經看過NHibernate.Transform提供了什麼,但沒有什麼突出的。

此外,這是不正確的做法嗎?

編輯:我設法通過訪問底層數據庫會話並從那裏執行我的標準來解決它。

ISession sess = ActiveRecordMediator.GetSessionFactoryHolder(). 
     CreateSession(typeof(ActiveRecordBase)); 
    ICriteria criteria = sess.CreateCriteria<Incident>("i") 
     .SetProjection(
      Projections.ProjectionList() 
       .Add(Projections.Property("i.Id"), "IncidentId") 
       .Add(Projections.Property("l.Id"), "LocationId") 
     ) 
     .CreateCriteria("Locations", "l") 
      .Add(Expression.Eq("l.PrimaryLocationFlag", "T")) 
     .SetResultTransformer(Transformers.AliasToBean<AuditReport>()); 

    return criteria.List<AuditReport>(); 

現在我想知道,是否有另一個實現這一點,而無需手動創建一個新的會話?

回答

1

如果您想要爲轉換結果使用類,那麼您可能需要將其「導入」到ActiveRecord。

嘗試裝潢任何AR類(或者也許是AuditReport,但它可能需要一個AR-裝飾類):

[Import(typeof(AuditReport), "AuditReport")] 

這將轉化爲在XML的配置NHibernate的進口屬性。

這HQL使用類結構的時候,像這樣ATLEAST解決這個問題:

+0

感謝您的答覆。我不幸在工作時錯過了這個回覆,所以明天我會試試。 – Mike 2010-07-28 02:13:33

+0

無論我在哪裏使用Import屬性,它仍然抱怨引用非AR類。查看文檔,看起來像Import屬性隻影響用HQL編寫的查詢。 http://www.castleproject.org/activerecord/documentation/v1rc1/manual/attributedocs/Generated_ImportAttribute.html – Mike 2010-07-28 12:55:55

+0

哦,好的,我很害怕這個。那麼,這值得一試。主動記錄在許多方面都有些癱瘓,我認爲你會發現自己直接使用直接的NHibernate(因爲你不能控制二級緩存或者在AR iirc中使用HQL。 – jishi 2010-07-29 08:44:10