日期:2014-05-18  浏览次数:20815 次

关于NHibernate1.2的一对多关关系表问题,解决一定结贴给分
请大家帮忙指点!
问题描述:我有2张表,LogicUsers和LogicArticle,其中LogicUsers为主表。我想要再LogicUsers.hbm.xml中配置one-to-many的关系,在LogicArticle里面配置many-to-one的关系,以达到两个有关联。可是,我配置子表的多对一后保存,没有问题。只要配置主表的一对多关系,保存,就提示无法保存对象。根据SQLServer   Profile监控,发现根本没有执行SQL语句,也就是说配置文件错误。请看以下代码
<?xml   version= "1.0 "   encoding= "utf-8 "   ?>
<hibernate-mapping   xmlns= "urn:nhibernate-mapping-2.2 "   namespace= "Schema "   assembly= "Schema ">
    <class   name= "LogicUsers "   table= "LogicUsers ">
        <id   name= "Id ">
            <column   name= "userid "   length= "40 "   sql-type= "varchar "   not-null= "true "   />
            <generator   class= "uuid.hex "   />
        </id>
        <property   name= "Name ">
            <column   name= "name "   length= "40 "   not-null= "false "/>
        </property>
        <property   name= "Pwd ">
            <column   name= "pwd "   length= "20 "   not-null= "false "/>
        </property>
<!--   设置一对多关系,删除这部分,下面的代码就能通过(子表已经配置了多对一)@_@   -->
        <set   name= "Children "   lazy= "true ">
            <key   column= "userid "   />
            <one-to-many   class= "LogicArticle "   />
        </set>
 
    </class>
</hibernate-mapping>

test.cs文件:
LogicUsers   m_LogicUser   =   new   LogicUsers();
m_LogicUser.Name   =   this.txtName.Text.Trim();
m_LogicUser.Pwd   =   this.txtPWD.Text.Trim();

LogicArticle   l1   =   new   LogicArticle();
l1.Title   =   this.txtTitle.Text.Trim();
l1.UserObject   =   m_LogicUser;   (此处为给子表的LogicUsers类型的属性复制)

ISessionFactory   sessionFactory   =   new   NHibernate.Cfg.Configuration().Configure().BuildSessionFactory();
ISession   session   =   sessionFactory.OpenSession();
ITransaction   transaction   =   session.BeginTransaction();

session.Save(m_LogicUser);     (通过监控发现此处未执行SQL)
session.Save(l1);
//   m_LogicUser.Children.Add(l1,   l1);   此处模仿其他网站上的资料,在主表中添加IDictionary,然后添加,同样无效
transaction.Commit();
session.Close();

------解决方案--------------------
应该是比较简单的,参考
http://www.hibernate.org/hib_docs/nhibernate/html/example-parentchild.html
------解决方案--------------------
友情up

------解决方案--------------------
try:

<set name= "Children " lazy= "true " cascade= "all " inverse= "true ">
<key column= "userid " />
<one-to-many class= "LogicArticle " />
</set>