Nhiberate (三)测试

(一)添加数据:

        public void AddUser(User user)
        {
            ISession session = NhibernateFactory.GetInstance().GetSession();
            session.Save(user);
            session.Flush();
        }

执行,报错“当 IDENTITY_INSERT 设置为 OFF 时,不能为表中的标识列插入显式值

把 User.hbm.xml文件中:

《generator》节点class 改为 "native":

<hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2"
                   assembly="UserInformation.Domin" 
                   namespace="UserInformation.Domin.Entities">
  <class name="UserInformation.Domin.Entities.User,UserInformation.Domin"
          table="UserInformation" >
    <id name="Id" 
        type="Int32" 
        unsaved-value="null">
      <generator class="native"></generator>
    </id>
    <property name="Name"></property>
    <property name="PassWord"></property>
    <property name="UserType"></property>
  </class>
  
</hibernate-mapping>

 (二)修改数据:

        /// <summary>
        /// 修改:
        /// </summary>
        /// <param name="id"></param>
        public void ModifyUser(int id)
        {
            ISession session = NhibernateFactory.GetInstance().GetSession();
            if (AllUser == null)
            {
                AllUser = GetUserList();
            }
            var result = AllUser.FirstOrDefault(x => x.Id == id);
            session.Update(result);
        }

        public void ModifyUser(User user)
        {
            ISession session = NhibernateFactory.GetInstance().GetSession();
            session.Update(user);
            session.Flush();
        }

  测试修改:

        [TestMethod]
        public void ModifyUserTest()
        {
            UserData userData = new UserData();
            var result = userData.GetUserList();
            var updatedUser = result.FirstOrDefault(x => x.Id == 33);
            updatedUser.Name = "改过以后的名称";
            userData.ModifyUser(updatedUser);
        }

 (三) 删除:

 public void DeleteUser(int id)
        {
            ISession session = NhibernateFactory.GetInstance().GetSession();
            if (AllUser == null)
            {
                AllUser = GetUserList();
            }
            var result = AllUser.FirstOrDefault(x => x.Id == id);
            session.Delete(result);
            session.Flush();
        }

        public void DeleteUser(User user)
        {
            ISession session = NhibernateFactory.GetInstance().GetSession();
            session.Delete(user);
            session.Flush();
        }

删除测试:

   [TestMethod]
        public void DeleteUserTest()
        {
            UserData userData = new UserData();
            var result = userData.GetUserList();
            var updatedUser = result.FirstOrDefault(x => x.Id == 32);
            userData.DeleteUser(updatedUser);
        }

执行可运行

 

posted @ 2016-11-07 17:32  pkyou  阅读(287)  评论(0编辑  收藏  举报