2

我有這樣的事情:NHibernate的QueryOver繼承

public class User 
    { 
     /* some properties */ 
     public virtual int Id { get; set; } 
     public abstract string LastName { get; } 

    } 
    public class Student 
    { 
     public virtual int Id { get; set; } 
     public virtual string LastName{ get; set; } 
    } 

    public class StudentUser : User 
    { 
     public virtual Student Student { set; get; } 

     public override string LastName 
     { 
      get { return Student.LastName; } 
     } 
    } 

    public class foo 
    { 
     public virtual int Id { get; set; } 

     public virtual IList<User> Users { get; set; } 
    } 


1. I would like to do the following using QueryOver : 
    var query = session.QueryOver<foo>(); 
     User User = null; 

//case 1: This is not working 
     query.JoinAlias(x=> x.Users ,() => User) 
       .Where(() => ((StudentUser)User).Student.LastName == "smith"); 

//case 2: Also This is not working 
     query.JoinAlias(x=> x.Users ,() => User) 
       .Where(() => ((StudentUser)User).LastName == "smith"); 

//case 3: This is working 
     query.JoinAlias(x=> x.Users ,() => User) 
       .Where(() => ((StudentUser)User).Id == 123); 

當我使用query.JoinAlias(x=> x.Users ,() => User)超過一次,我得到這個例外An item with the same key has already been added

而且我得到這個異常:無法解析屬性:的Student.LastName:Entities.User的情況下,1和2的情況下

但它正在與Id屬性(案例3)

它可能看起來像:

SELECT  * 
FROM   Foo INNER JOIN 
         Users ON Foo.Id = Users.FooId_FK INNER JOIN 
         Students ON Users.StudentId_FK = Students.Id 
where Students.LastName = 'smith' 

我怎樣才能得到LastName屬性值?

+0

請問StudentUser的只讀視圖和可寫一個好嗎?是否所有的學生和類似的用戶? – Firo 2014-09-30 10:44:16

+0

你能展示你的映射嗎? – 2014-09-30 13:24:01

回答

2

認爲這應該工作:

session.QueryOver<foo>() 
    .JoinQueryOver(f => f.Users) 
    .JoinQueryOver(u => ((StudentUser)u).Student) 
     .Where(st => st.LastName == "smith") 

或用JoinAlias保持:

User userAlias = null; 
Student studentAlias = null; 

session.QueryOver<foo>() 
    .JoinAlias(f => f.Users,() => userAlias) 
    .JoinAlias(() => ((StudentUser)userAlias).Student,() => studentAlias) 
     .Where(() => studentAlias.LastName == "smith") 
+0

哇,這真的與QueryOver一起嗎?涼! ;)表達式解析器與鑄造...必須愛NHibernate ... ... – 2014-09-30 14:08:20

+0

@RadimKöhler:是的,你可以用選擇做到這一點,我90%確定你可以用連接做到這一點...沒有OP的映射很難測試和知道 – 2014-09-30 14:09:34

+0

謝謝@AndrewWhitaker,它工作的很完美..另一個問題,當我使用相同的連接多次(.JoinAlias(f => f.Users,()=> userAlias)),我得到這個異常「一個具有相同密鑰的項目已被添加」 我該怎麼辦? – NH89 2014-09-30 14:46:36