Nhibernate中CreateSQLQuery用法实例

Nhibernate中CreateSQLQuery用法实例:

涉及的表:

Cake{

Id ,

CakeName

。。。。

}

CakeSize{

CakeId,-为外键,对应Cake表的字段Id

Size

}

(其中ISession session = NHibernateHelper.GetCurrentSession();)

用法一(返回数值):
ISQLQuery query = session.CreateSQLQuery("SELECT COUNT(Id) AS C FROM Cake").AddScalar("C", NHibernateUtil.Int32);
int c = Convert.ToInt32(query.UniqueResult());
或int c = query.UniqueResult<int>;//使用此方法发现sql执行了两次,故不推荐使用。


用法二(返回对象实体):
ISQLQuery query = session.CreateSQLQuery("select * from cake c").AddEntity("CAKE.DataTransfer.Entities.Cake");
或ISQLQuery query = session.CreateSQLQuery("select * from cake c").AddEntity("c", "CAKE.DataTransfer.Entities.Cake");
或ISQLQuery query = session.CreateSQLQuery("select * from cake c").AddEntity(typeof(Cake));
或ISQLQuery query = session.CreateSQLQuery("select * from cake c").AddEntity("c", typeof(Cake));
或ISQLQuery query = session.CreateSQLQuery("select * from cake c").AddEntity("c", typeof(Cake), LockMode.Write);

IList<Cake> c = query.List<Cake>();

用法三(连表查询):
ISQLQuery query = session.CreateSQLQuery("select cs.* from cake c join CakeSize cs on cs.CakeId=c.Id")
    .AddEntity("cs", typeof(CakeSize));
IList<CakeSize> cs = query.List<CakeSize>();

posted on 2008-12-28 19:46  张皓  阅读(6505)  评论(0编辑  收藏  举报

导航