📜  NHibernate-基本的CRUD操作

📅  最后修改于: 2020-11-19 05:32:11             🧑  作者: Mango


在本章中,我们将介绍基本的CRUD操作。既然我们的系统已经准备好启动,并且已经成功实现了我们的域Student类,那么我们还定义了映射文件并配置了NHibernate。现在,我们可以使用一些查询来执行CRUD操作。

建立资料

如您所见, NHibernateDemoDB数据库的Student表中没有数据。

NHibernate DemoDB

因此,要添加一些数据,我们需要执行添加/创建操作,如下所示。

using (var session = sefact.OpenSession()) { 

   using (var tx = session.BeginTransaction()) { 
     
      var student1 = new Student { 
         ID = 1, 
         FirstMidName = "Allan", 
         LastName = "Bommer" 
      }; 
      
      var student2 = new Student { 
         ID = 2, 
         FirstMidName = "Jerry", 
         LastName = "Lewis" 
      }; 
      
      session.Save(student1); 
      session.Save(student2); 
      tx.Commit(); 
   } 
   
   Console.ReadLine(); 
}

如您所见,我们已经创建了两个学生,然后调用OpenSession的Save()方法,然后调用BeginTransaction的Commit()。这是Program.cs文件中的完整实现

using NHibernate.Cfg; 
using NHibernate.Dialect; 
using NHibernate.Driver; 

using System; 
using System.Linq; 
using System.Reflection;

namespace NHibernateDemoApp { 
   
   class Program { 
      
      static void Main(string[] args) { 
         var cfg = new Configuration();
            
         String Data Source = asia13797\\sqlexpress;
         String Initial Catalog = NHibernateDemoDB;
         String Integrated Security = True;
         String Connect Timeout = 15;
         String Encrypt = False;
         String TrustServerCertificate = False;
         String ApplicationIntent = ReadWrite;
         String MultiSubnetFailover = False;
            
         cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source + 
            Initial Catalog + Integrated Security + Connect Timeout + Encrypt +
            TrustServerCertificate + ApplicationIntent + MultiSubnetFailover"; 

            x.Driver(); 
            x.Dialect(); 
         }); 
   
         cfg.AddAssembly(Assembly.GetExecutingAssembly()); 
         var sefact = cfg.BuildSessionFactory(); 
            
         using (var session = sefact.OpenSession()) { 
            
            using (var tx = session.BeginTransaction()) { 
               
               var student1 = new Student { 
                  ID = 1,  
                  FirstMidName = "Allan", 
                  LastName = "Bommer" 
               }; 

               var student2 = new Student { 
                  ID = 2, 
                  FirstMidName = "Jerry", 
                  LastName = "Lewis" 
               }; 
            
               session.Save(student1); 
               session.Save(student2); 
               tx.Commit();
            } 
            
            Console.ReadLine(); 
         } 
      } 
   } 
}

现在,让我们运行此应用程序,然后转到SQL Server对象资源管理器并刷新数据库。您将看到上述两个学生现在已添加到NHibernateDemoDB数据库的Student表中。

SQL Server对象

从学生表读取数据

您可以看到,现在我们的学生表中有两个记录。要从表中读取这些记录,我们需要调用OpenSession的CreateCriteria() ,如以下代码所示。

using (var session = sefact.OpenSession()) { 
   
   using (var tx = session.BeginTransaction()) { 
      var students = session.CreateCriteria().List(); 
      
      foreach (var student in students) { 
         Console.WriteLine("{0} \t{1} \t{2}", 
            student.ID,student.FirstMidName, student.LastName); 
      } 
      
      tx.Commit(); 
   } 
   
   Console.ReadLine(); 
}

因此,如果您想要记录列表,那么我们只需说出Student类型的列表即可。

现在,对所有学生使用foreach ,并说在控制台上打印ID, FirstMidNameLastName 。现在,让我们再次运行该应用程序,您将在控制台窗口中看到以下输出。

1 Allan Bommer
2 Jerry Lewis

您还可以使用以下代码通过在OpenSession的Get()方法中指定ID来检索任何记录。

using (var session = sefact.OpenSession()) { 
   
   using (var tx = session.BeginTransaction()) { 
      var students = session.CreateCriteria().List(); 
      
      foreach (var student in students) { 
         Console.WriteLine("{0} \t{1} \t{2}", student.ID, 
            student.FirstMidName, student.LastName); 
      }
      
      var stdnt = session.Get(1); 
      Console.WriteLine("Retrieved by ID"); 
      Console.WriteLine("{0} \t{1} \t{2}", stdnt.ID, 
         stdnt.FirstMidName, stdnt.LastName); 
      tx.Commit();
   } 
    
   Console.ReadLine(); 
}

现在,当您运行应用程序时,将看到以下输出。

1 Allan Bommer
2 Jerry Lewis
Retrieved by ID
1 Allan Bommer

更新记录

要更新表中的记录,我们需要首先获取该特定记录,然后通过调用OpenSession的Update()方法来更新该记录,如以下代码所示。

using (var session = sefact.OpenSession()) { 

   using (var tx = session.BeginTransaction()) { 
      var students = session.CreateCriteria().List(); 
     
      foreach (var student in students) { 
         Console.WriteLine("{0} \t{1} \t{2}", student.ID, 
            student.FirstMidName, student.LastName); 
      }
      
      var stdnt = session.Get(1); 
      Console.WriteLine("Retrieved by ID"); 
      Console.WriteLine("{0} \t{1} \t{2}", stdnt.ID, stdnt.FirstMidName, stdnt.LastName);
      
      Console.WriteLine("Update the last name of ID = {0}", stdnt.ID); 
      stdnt.LastName = "Donald"; 
      session.Update(stdnt); 
      Console.WriteLine("\nFetch the complete list again\n"); 
      
      foreach (var student in students) { 
         Console.WriteLine("{0} \t{1} \t{2}", student.ID, 
            student.FirstMidName, student.LastName); 
      } 
      
      tx.Commit();
   } 
   
   Console.ReadLine();
}

现在,当您运行应用程序时,将看到以下输出。

1 Allan Bommer
2 Jerry Lewis
Retrieved by ID
1 Allan Bommer
Update the last name of ID = 1
Fetch the complete list again
1 Allan Donald
2 Jerry Lewis

如您所见,ID为1的LastName从Bommer更新为Donald。

删除记录

要从表中删除任何记录,我们需要首先获取该特定记录,然后通过调用OpenSession的Delete()方法删除该记录,如以下代码所示。

using (var session = sefact.OpenSession()) { 
   
   using (var tx = session.BeginTransaction()) { 
      var students = session.CreateCriteria().List();
      
      foreach (var student in students) { 
         Console.WriteLine("{0} \t{1} \t{2}", student.ID, 
            student.FirstMidName, student.LastName); 
      }
      
      var stdnt = session.Get(1); 
      Console.WriteLine("Retrieved by ID"); 
      Console.WriteLine("{0} \t{1} \t{2}", stdnt.ID, stdnt.FirstMidName, stdnt.LastName);
      
      Console.WriteLine("Delete the record which has ID = {0}", stdnt.ID); 
      session.Delete(stdnt);
      Console.WriteLine("\nFetch the complete list again\n"); 
      
      foreach (var student in students) { 
         Console.WriteLine("{0} \t{1} \t{2}", student.ID, student.FirstMidName, 
            student.LastName); 
      } 
      
      tx.Commit();
   } 
    
   Console.ReadLine(); 
}

现在,当您运行应用程序时,将看到以下输出。

1 Allan Donald
2 Jerry Lewis
Retrieved by ID
1 Allan Bommer
Delete the record which has ID = 1
Fetch the complete list again
2 Jerry Lewis

如您所见,ID等于1的记录在数据库中不再可用。您还可以在SQL Server对象资源管理器中查看数据库。

对象资源管理器