NH3.X与2.X使用上的一些区别
NH用了很長時間一直都是用2.X版本,今天體驗了一下3.3。記錄一下兩者使用上的一些區(qū)別。
一、代理
//2.x 寫法 <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>//3.X寫法 <property name='proxyfactory.factory_class'>NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate</property>因為3.X已經(jīng)內(nèi)部集成proxy generator,因此無需另外的NHibernate.ByteCode.LinFu.dll or NHibernate.ByteCode.Castle.dll了。
?
二、延遲加載
public class Childpublic class Parent {Public virtual Child Child{get;set;} }Parent p=XXXXXXX; If (p.Child is Child) { //do something }
由于有代理的延遲加載,p.Child并不是Child類型。此處的is判斷是false。
NH3.X的Parent Map文件中<many-to-one name="Child" lazy="no-proxy"/>將會有兩個效果
三、Hql寫法的變更
2.X刪除數(shù)據(jù)的寫法
ISession session= GetSession(); string hql = "from table1 tab where DataTime between :a and :b"; IType[] itypes = new IType[] { NHibernateUtil.DateTime, NHibernateUtil.DateTime }; session().Delete(hql, new object[] { startDate, endDate }, itypes);以上的寫法在3.X中會產(chǎn)生異常: KeyNotFoundException: 給定關(guān)鍵字不在字典中。
?
3.X寫法1:放棄參數(shù)命名,全部用?代替,閱讀性不是太好。
ISession session= GetSession(); string hql = "from table1 tab where DataTime between ? and ?"; IType[] itypes = new IType[] { NHibernateUtil.DateTime, NHibernateUtil.DateTime }; session().Delete(hql, new object[] { startDate, endDate }, itypes);3.X寫法2:該方法與上一種差不多,但在hql中聲明了是delete操作。
string hql = "delete from table1 tab where DataTime between ? and ?"; IType[] itypes = new IType[] { NHibernateUtil.DateTime, NHibernateUtil.DateTime }; IQuery q = session.CreateQuery(hql); for (int i = 0; i < vals.Length; i++) {q.SetParameter(i, vals[i], itypes[i]); } q.ExecuteUpdate();?
3.X寫法3:每個hql參數(shù)用SetXXType顯式賦值。
string hql = "delete from table1 tab where DataTime between :start and :end"; IType[] itypes = new IType[] { NHibernateUtil.DateTime, NHibernateUtil.DateTime }; IQuery q = session.CreateQuery(hql); q.SetDateTime(“start”,a); q.SetDateTime(“end”, b); q.ExecuteUpdate();雖然SetParameter重載了多個方法,但position只能用于“?”聲明的hql,name只能用于命名參數(shù)的hql。否則會產(chǎn)生異常。
IQuery SetParameter(int position, object val, IType type);IQuery SetParameter(string name, object val, IType type);?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/Byeah/archive/2013/03/25/2981093.html
總結(jié)
以上是生活随笔為你收集整理的NH3.X与2.X使用上的一些区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redmi K50系列终极之作跑分首秀:
- 下一篇: PeerJS 0.1.7:一个用于浏览器