nHibernate加入

时间:2011-06-29 06:53:45

标签: nhibernate nhibernate-criteria

我是NHibernate的新手。是否可以为以下方案创建标准?

public class A{
    public string name {get; set;}
}

public class B {
    public string name {get; set;}
}

public class C {
    public string firstname {get; set;}
    public string lastname {get; set;}
}

最终我想构建以下查询

SELECT a.*, b.*, c.* FROM A AS a
INNER JOIN B as b ON a.id = b.Id 
INNER JOIN C AS c ON b.id = c.Id
WHERE o.lastname like '%ted%' 
OR c.firstname like '%test%' 
OR b.name like '%test%' 
OR a.name like '%test%'

根据作者的评论编辑:类。

public class A 
{ 
  public string aname {get; set;} 
  public string aId {get; set;} 
} 

public class B 
{ 
  public string bId {get; set;} 
  public string bname {get; set;} 
} 

public class C
{ 
  public string firstname {get; set;} 
  public string lastname {get; set;} 
}

2 个答案:

答案 0 :(得分:0)

我认为这与你所追求的非常接近。可能存在创建多个“或”标准的更优雅方式。我假设你上面的类实际上有id并互相引用,因为它们不包含在上面的基本类中。

        ICriteria criteria = Session.CreateCriteria(typeof(a));

        criteria.CreateAlias("a.Id", "b", JoinType.InnerJoin);
        criteria.CreateAlias("b.Id", "c", JoinType.InnerJoin);

        criteria.Add(
            Expression.Or(

                Expression.Or(
                    Expression.Like("c.LastName", "Ted"),
                    Expression.Like("c.LastName", "Test")),

                Expression.Or(
                    Expression.Like("b.Name", "Ted"),
                    Expression.Like("a.Name", "Test"))
            )
        );

        criteria.List();

我假设你的类模型应该基于你的sql语句

public class A
{    
public string name {get; set;}
public B Id {get; set;}
}

public class B 
{    
public C Id {get; set;}
public string name {get; set;}
}

public class C 
{    
public string firstname {get; set;}    
public string lastname {get; set;}
}

答案 1 :(得分:0)

这可能会有所帮助

private IQueryOver<parententity>GetQuery(string nameA ,string nameB,string fname , string lname ){
          Conjuction Acon = Restriction.Conjunction;conjuction Bcon = Restriction.Conjunction;
          Conjuction Ccon = Restriction.Conjunction;

 if(string.isNullOrEmpty(nameA))
    Acon.Add(Restrictions.Like(Projections<Aentity>(x => x.name), nameA),MatachMode.Any););
 if(string.isNullOrEmpty(nameB))
    Acon.Add(Restrictions.Like(Projections<Bentity>(x => x.name), nameB),MatachMode.Any););
 if(string.isNullOrEmpty(fname))
    Acon.Add(Restrictions.Like(Projections<Centity>(x => x.Fname), Fname),MatachMode.Any););
 if(string.isNullOrEmpty(Lname))
    Acon.Add(Restrictions.Like(Projections<Centity>(x => x.Lname), Lname),MatachMode.Any););

       IQueryOver<Aentity> query = NHSession.QueryOver<AEniity>()
                  .where(Acon)
                  .joinQueryOver(x => x.Bcon)
                  .where(Bcon)
                  .joinQueryOver(x=> c.Ccon)
                  .where(Ccon);   

             return query;

}