All together to learn Nhibernate+nunit (Vs2012+sql Server2008)

Source: Internet
Author: User
Tags assert generator

All together to learn Nhibernate+nunit (Vs2012+sql Server2008)

Category: C#2013-08-10 18:47 1589 people read reviews (5) Favorite reports

Nhibernatenunitvisual Studio 2012

If you have not heard of NHibernate or NUnit, then, congratulations, like me, shake hands. If you are already an old soy sauce, that dear different do not take you to play, please consciously detour,,,. I would like to dedicate this article to a vast and small white fellow such as myself (APPLAUSE)!

Say 2013 a certain day, listen to a martial arts elder mention NHibernate, small white I suddenly brain blank, this is a what is ah, in a strong curiosity driven, I decided to go to dinner first, come back after this thing forget, ... Here I just want to say: I didn't mean! A few days ago, and I heard rumors, saying Outmann play small monsters, the use of the moves there is nhibernate andnunit, this small white I can long memory, why NI? Because like me the vast number of small white's ultimate desire is the poor and extremely lifelong learning, down the earth all the ghosts and goblins ah. Words do not say, immediately provoke Google degrees Niang torture, according to the "frankly lenient, Cong" principle, the two boys NHibernate and nunit of the activities of 1510 all recruit out, my heart is very comforting ah ... Originally nhibernate originated from the Java school, one of the three most prestigious framework ssh: Hibernate. Well, if you're just as cynical about Java school as I am, then I'm going to talk nonsense: first of all, you have to understand that the role of nhibernate in. NET is the same as Hibernate in Java; second, they are open source; Thirdly, they are a kind of Object Relational database mapping framework. 3rd Good Understanding Oh, "Object",. NET and Java are object-oriented, the popular point is that there are all kinds of class classes; "Relational database", MS sql,oracle,etc, refers to them; "Mappings", It means hibernate has built a bridge between the relational database and our object-oriented class. So, with this, we can easily use object-oriented thinking to write the data layer, as to how the data layer to deal with the database, it is to hibernate to deal with. What about NUnit? This simple, plainly speaking, on a test tool, we write a good test code inside, the program automatically help us do the test, roar. Said so much, in fact, I also do not understand, you really understand not understand ..., at this point, if the vast number of compatriots in the mind is still not a hint of waves, then please yourself to torture a Google degree Niang bar.

Because NHibernate and nunit things really too much, and small white I have limited skill, so, to recommend two very good blog, which is written in detail:

1,nhibernate Tour Series article navigation http://www.cnblogs.com/lyj/archive/2008/10/30/1323099.html

2,nhibernate from getting started to mastering series http://www.cnblogs.com/GoodHelper/archive/2011/02/14/nhiberante_01.html

Some of the contents of the two blogs overlap, but I still suggest that everyone read it from beginning to end, after all, we are small white,

But two blog thousand good million good, only a little bad, is the age, the example inside a lot of local grammar has changed, this can put my little friend stunned,. Fortunately small white my heart quality good, after some pondering, finally all fix, next Tuesday on the Tanabata, I also didn't what good send, take everyone together to do a nhibernate+nunit demo bar,

Development environment: VS, SQL Server 2008,nhibernate 3.3.3, NUnit 2.6.2

Nhibernate:nhibernate Forge

Nunit:nunit

Of course, I will take demo+nhibernate3.3.3+nunit 2.6.21 Pack, you can go directly to download.

Demo:demo

Here's the official start:

1, open VS2012, New project, select Class Library, named: Domain. Are you sure

2, delete your own Class1.cs, and create a new student class. The code is as follows:

[CSharp] view plaincopyprint?

  1. Using System;
  2. Using System.Collections.Generic;
  3. Using System.Linq;
  4. Using System.Text;
  5. Using System.Threading.Tasks;
  6. Namespace Domain
  7. {
  8. <summary>
  9. Student class
  10. </summary>
  11. public class Student
  12. {
  13. <summary>
  14. Id
  15. </summary>
  16. public virtual int ID {get; set;}
  17. <summary>
  18. Student Name
  19. </summary>
  20. Public virtual string Name {get; set;}
  21. <summary>
  22. Student Sex
  23. </summary>
  24. Public virtual string Sex {get; set;}
  25. <summary>
  26. Student Age
  27. </summary>
  28. public virtual int Age {get; set;}
  29. }
  30. }

3, add an XML file named: Student.hbm.xml,

At this point, the directory structure is like this:

4. Write the Student.hbm.xml mapping file with the following code:

[HTML] view Plaincopyprint?

    1. <?xml version= "1.0" encoding= "Utf-8"?>
    2. <class name=" Student "table=" t_student "lazy=" true ">
    3. <id name=" id "column=" id "unsaved-value=" 0 ">
    4. <generator class=" native "&G t;</generator>
    5. </id>
    6. <property name= "name" type= "string" column= "Stuname" length= " "Not-null=" true "></property>
    7. <property name=" Sex "type=" string "column=" Stusex "length=" 2 " ></property>
    8. <property name= "age" type= "Int32" column= "Stuage" ></property>
    9. & lt;/class>

The compilation of the XML map file is a key step in nhibernate, and if you don't read the two blog posts, you probably don't understand it. Note: Before you write the XML file, remember to place the nhibernate-mapping.xsd files and nhibernate-configuration.xsd files in the downloaded nhibernate to C:\Program files (x86) \ Microsoft Visual Studio 11.0\xml\schemas directory (my is Win7 64, because the machine is different, if not know where to put, Baidu next bar), so, when writing Xml file, vs will have smart hints.
5. Right-click on the Student.hbm.xml file and select Properties to change the Build Action property of the XML file from "content" to "Embedded Resource". Such as:

6, right click on the project solution, choose Add New Project, add a new class library, named: Nhibernatetest. (In fact, this is where we use unit to test units)

Delete the default Class1.cs from the new class library, at which point the directory structure is:

7, in the Nhibernatetest project, add a reference to the Domain class library we just created, and add references to the NHibernate and NUnit assemblies we downloaded.

Once the reference is added, it looks like this,

10, copy and paste the MSSQL.cfg.xml file under the Configuration_templates folder in the downloaded NHibernate to the Nhibernatetest class library and rename it as: Hibernate.cfg.xml and modify the file as follows:

[HTML] view Plaincopyprint?

  1. <?xml version= "1.0" encoding= "Utf-8"?>
  2. <!--
  3. This template is written to work with Nhibernate.test.
  4. Copy the template to your Nhibernate.test project folder and rename it in Hibernate.cfg.xml and change it
  5. For your own use before compile tests in VisualStudio.
  6. -
  7. <!--the System.Data.dll provider for SQL Server--
  8. <session-factory name= "Nhibernate.test" >
  9. <property name= "Connection.driver_class" >NHibernate.Driver.SqlClientDriver</property>
  10. <property name= "Connection.connection_string" >
  11. server= (local); Initial catalog=nhibernate;integrated Security=sspi
  12. </property>
  13. <property name= "dialect" >NHibernate.Dialect.MsSql2008Dialect</property>
  14. <!--Add the following line of code, in addition, no other changes, of course, you can also modify the above database link string--
  15. <mapping assembly= "Domain"/>
  16. </session-factory>

Then, right-click on the Hibernate.cfg.xml file, select Properties, and modify the copy of the XML file to the input directory property to: Always copy

11. Add the NHibernateTest.cs class with the following code:

[CSharp] view plaincopyprint?

  1. Using System;
  2. Using System.Collections.Generic;
  3. Using System.Linq;
  4. Using System.Text;
  5. Using System.Threading.Tasks;
  6. Using NHibernate;
  7. Using NHibernate.Tool.hbm2ddl;
  8. Using Nunit.framework;
  9. Namespace Nhibernatetest
  10. {
  11. [Testfixture]
  12. public class Nhibernateinit
  13. {
  14. [Test]
  15. public void Inittest ()
  16. {
  17. var cfg = new NHibernate.Cfg.Configuration (). Configure (System.AppDomain.CurrentDomain.BaseDirectory + "\\hibernate.cfg.xml");
  18. New Schemaexport (CFG). Execute (True, true, false);
  19. using (isessionfactory sessionfactory = cfg. Buildsessionfactory ()) {}
  20. }
  21. }
  22. }

12. Open SQL Server 08 and create a new NHibernate database

[SQL] view plaincopyprint?

    1. Create DATABASE NHibernate

13, right-click on the Nhibernatetest class library, select Properties, Switch to "Debug" tab, "Start External debugging", browse, select Nunit.exe program. (Note: If you have installed the NUnit 2.6.2.msi program that you downloaded at the beginning of the article), the effect is as shown:


14, click "Save All", then right click on the entire project solution and select "Build Solution". Then, right-click the Nhibernatetest class library and set it as the startup project. F5, running the program

At this point, we see that NUnit.exe has started, in the NUnit window, select: "File", "New Project", the file name is: Nhibernatetest.nunit, click Save. At this point, the window still has nothing. Then select: "Project", "ADD assembly", in the popup dialog box, locate our Nhibernatetest class library generated DLL file, click Open, such as:

15, click the Run button in the NUnit window, and NUnit will automatically execute the methods in our Nhibernatetest class library. At this point, the window should look like the following:

16, at this point, open the database, we will find that our t_student data sheet has been automatically created.

Little friends, have you been stunned? Isn't that amazing stuff? Ha ha...... I find writing an article really a physical activity, can't stand it ...

Alas, no way, the spirit of the vast number of small partners dutifully responsible for the high sense of mission, small white I decided to continue the code word ... Acclamation

This test, every time we have to start the external program NUnit, I believe that some small partners do not like, rest assured that we can install the plug-in way to solve this problem (note: This process requires networking).

In VS2012, select: "Tools" = "Extensions and Updates", in the dialog box that pops up, click the "Online" tab, and then in the Search box, enter: "NUnit", carriage return, as shown in the effect:

Select "Download", after the download is complete, you will be prompted to install, you directly choose to install it. Once the installation is complete, restart vs. After rebooting, select: Test-Window-Test Explorer on the menu bar. Then rebuild the entire project solution, and we'll see our nhibernatetest test class in the Test Explorer. Here, we can choose to run all, or you can right-click on a separate method and choose Run or Debug.

Next, I wrote several new test methods, respectively, to the T_student table to save data, take out the data. The NHibernateInit.cs file code is as follows:

[CSharp] view plaincopyprint?

  1. Using System;
  2. Using System.Collections.Generic;
  3. Using System.Linq;
  4. Using System.Text;
  5. Using System.Threading.Tasks;
  6. Using NHibernate;
  7. Using NHibernate.Tool.hbm2ddl;
  8. Using Nunit.framework;
  9. Namespace Nhibernatetest
  10. {
  11. [testfixture]//defines a test class that can contain many test functions and initialization and destruction functions.
  12. public class Nhibernateinit
  13. {
  14. [test]//defines a separate test function.
  15. public void Inittest ()
  16. {
  17. var cfg = new NHibernate.Cfg.Configuration (). Configure (System.AppDomain.CurrentDomain.BaseDirectory + "\\hibernate.cfg.xml");
  18. New Schemaexport (CFG). Execute (True, true, false);
  19. using (isessionfactory sessionfactory = cfg. Buildsessionfactory ()) {}
  20. }
  21. Private Isessionfactory _sessionfactory;
  22. [setup]//defines the test function initialization function, which is called once before each test function is run.]
  23. public void Initsessionfactory ()
  24. {
  25. var cfg = new NHibernate.Cfg.Configuration (). Configure (System.AppDomain.CurrentDomain.BaseDirectory + "\\hibernate.cfg.xml");
  26. _sessionfactory = cfg. Buildsessionfactory ();
  27. }
  28. [Test]
  29. public void Savetest ()
  30. {
  31. var stu = new Domain.student ()
  32. {
  33. Name = "Zhang San",
  34. Sex = "M",
  35. Age = 20
  36. };
  37. using (ISession session = _sessionfactory.opensession ())
  38. {
  39. Try
  40. {
  41. Object obj = Session. Save (Stu);
  42. Session. Flush ();
  43. Assert.notnull (obj);
  44. }
  45. catch (Exception ex)
  46. {
  47. Throw ex;
  48. }
  49. }
  50. }
  51. [Test]
  52. public void Selecttest ()
  53. {
  54. using (ISession session = _sessionfactory.opensession ())
  55. {
  56. Domain.student stu = Session. Get<domain.student> (1);
  57. Assert.notnull (Stu);
  58. Console.WriteLine (Stu. Name);
  59. }
  60. }
  61. }
  62. }

The test results are as follows:

OK, so far, is the Nhibernate+nunit demo of the full demonstration, I do not know that the small partners to understand it? At the end, no more nagging: Cherish life, away from it ....

Note: For the difference between using the Nunit test and the MS Test framework, you can go to one of the articles I reprinted: The difference between the Nunit test and MS tests

All together to learn Nhibernate+nunit (Vs2012+sql Server2008)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.