2012-05-24 49 views
6

我有域類位置Nhibernate的投影超過嵌套嵌套屬性

public abstract class BaseEntity<T> where T: struct 
    { 
    public virtual T Id { get; set; } 
    public virtual bool Equals(BaseEntity<T> other) 
    } 

    public class Location : BaseEntity<Int32> 
    { 

    public User User {get;set;} 
    } 

    public class User : BaseEntity<Int32> 
    { 
    public string Name {get;set; 
    } 

    public OtherInfo Otherinfo {get;set;}; 
    } 
    public class OtherInfo 
    { 
    public string preference {get;set;}; 
    } 

    var criteria = session.CreateCriteria(typeof(Location), "alias"); 
    criteria.CreateCriteria("User", "user", JoinType.InnerJoin); 
    criteria.CreateCriteria("user.Otherinfo", "userInfo",JoinType.InnerJoin); 
    criteria.Add(Restrictions.Eq("user.Id", 100)); 
    criteria.SetProjection(Projections.Alias(Projections.Id(), "Id"),       Projections.Alias(Projections.Property("user.Name"), "Name"), Projections.Alias(Projections.Property("userInfo.preference "), "pref")); 

現在當我執行上述標準,它給出了關於userInfo.preference錯誤。 {NHibernate.QueryException:無法解析屬性:Otherinfo:Location.User 這裏有什麼錯誤。是不是因爲多嵌套對象

回答

4

使用CreateAlias代替:

criteria.CreateAlias("User", "user", JoinType.InnerJoin); 
criteria.CreateAlias("user.Otherinfo", "userInfo",JoinType.InnerJoin); 
+0

這只是我的錯字,而發佈的問題,在代碼中它的正確。 – Techmaster

+0

你有沒有其他線索,請讓我知道,我很長時間以來感到震驚。 – Techmaster

+0

是的 - 使用CreateAlias代替CreateCriteria - CreateCriteria會將你向下移動關聯,CreateAlias更自然 - 更新示例 –

3

這是別人找嵌套預測和嵌套與NHibernate標準加入:

public class A 
{ 
    public B {get;set;} 
    public string PropertyA {get;set;} 
} 
public class B 
{ 
    public C {get;set;} 
}  
public class C 
{ 
    public string CName {get;set;} 
} 
//you want to project and join 3 tables querying from A and get CName of C 
// InstanceA.B.C.CName 

你不能使用」。 「點作爲你的別名+你只能在一個別名內訪問1級(aliasA.PropertyA)

//you have to create 3 alias for each class/instance/table 
DetachedCriteria joinNested3tables = DetachedCriteria.For<A>("aliasA") //level 1 alias 
      .CreateAlias("aliasA.B", "aliasB", JoinType.InnerJoin) //level 2 alias 
      .CreateAlias("aliasB.C", "aliasC", JoinType.InnerJoin) //level 3 alias 
      .SetProjection(Projections.ProjectionList() 
      .Add(Projections.Property("aliasC.CName"), "CNameProjection") 
      //you cannot have more than 1 dot operator like below 
      //.Add(Projections.Property("aliasB.C.CName"), "CNameProjection") 
      );