0

我是NHibernate的新手,我使用的v4.0.30319甚至似乎沒有出現在官方網站(我不明白爲什麼?)所以我有麻煩找到好的文檔。NHibernate 4左外部加入一個單一的查詢數據庫

我想要的是理論上很簡單。我有3個表:

  • 客戶
  • ClientAnswer
  • 問題表問題

所以我有問題,在客戶我有客戶,並在連接表ClientAnswer我有一個客戶對每個問題的答案(如果有的話)。可能是因爲客戶端還沒有回答問題,所以它在ClientAnswer中沒有排。

我使用FluentNHibernate映射,它的如下:

public ClientMap() 
    { 
     Id(x => x.Id); 
     Map(x => x.Name).Not.Nullable(); 
     Map(x => x.Notes).Nullable(); 
     Map(x => x.IsDeleted).Not.Nullable(); 
    } 


public QuestionMap() 
    { 
     Id(x => x.Id); 
     Map(x => x.Description).Not.Nullable(); 
     Map(x => x.IsDeleted).Not.Nullable(); 
    } 

public ClientAnswerMap() 
    { 
     Id(x => x.Id); 
     Map(x => x.Value).Not.Nullable(); 
     Map(x => x.IsDeleted).Not.Nullable(); 

     References<Client>(x => x.Client, "ClientId"); 
     References<Driver>(x => x.Question, "QuestionId"); 
    } 

我想實現返回CustomThing列表的功能,所以每個CustomThing將包含一個問題和特定的客戶的回答(如果有的話,否則爲空)。

IEnumerable<CustomThing> GetQuestionsAndAnswers(int clientId) 

是我的自定義對象一樣簡單

public class CustomThing 
{ 
    public Question Question { get; set; } 
    public ClientAnswer ClientAnswer { get; set; } //it could be null 
} 

在SQL我可以這樣做:

SELECT * FROM詢問Q 左外連接ClientAnswer CA 上ca.QuestionId = q.Id

然後以某種方式篩選出ClientId不是我正在查找的客戶端的ClientAnswers,並將res ULT在CustomThing的枚舉中。 (我希望我適當解釋)

我願意接受任何建議,我與SQL :)

謝謝你不好,

編輯:我目前所面對的這一點。但它看起來效率很低,並且有多個對數據庫的訪問。但在情況下,它顯示了我想什麼想法有:

public IEnumerable<CustomThing> GetQuestionsAndAnswers(int clientId) 
    { 
     IList<Question> allQuestions = _session.QueryOver<Question>() 
      .WhereNot(x => x.IsDeleted).List(); 

     IList<CustomThing> customThings= new List<CustomThing>(); 

     foreach (Question q in allQuestions) 
     { 
      CustomThing customThing= new CustomThing(); 
      customThing.Question = q; 
      customThing.ClientAnswer= GetClientAnswer(clientId, q.Id); 

      customThings.Add(customThing); 
     } 

     return customThings; 
    } 

    private ClientAnswer GetClientAnswer(int clientId, int questionId) 
    { 
     var clientAnswer = _session.QueryOver<ClientAnswer>() 
      .Where(x => x.Client.Id == clientId) 
      .Where(x => x.Question.Id == questionId) 
      .WhereNot(x => x.IsDeleted).SingleOrDefault(); 

     return clientAnswer; //can be null if the client did not answer this question 
    } 

回答