Tutorials on FluentNHibernate with ASP.NET MVC and SQL Server. Part 1
What will happen? Lessons on FluentNHibernate on the example of a book site, where we will be able to view information about a book, display a list of books, filter it by genre, search by name, and also add, edit, delete books. All types of table relationships (one-to-one, one-to-many, many-to-many), creating, editing, deleting records, filtering, searching, displaying page by page will be considered. Programs used in the lessons: Visual studio 2013, SQL Server 2008 Manager Studio.
For a quick introduction to the simple CRUD operation with NHibernate and MVC, I recommend reading the following article in English: www.dotnetjalps.com/2014/07/fluent-nhibernate-asp-net-mvc-crud.html .
Also useful articles can be found here:github.com/jagregory/fluent-nhibernate/wiki/Getting-started (Eng); and its translation: habrahabr.ru/post/125135 .
More links in Russian: slynetblog.blogspot.com/2009/10/nhibernate-1.html
Table of Contents
Part 1. Launching the first application
Part 2. Creating classes, mapping and populating the database
1. STARTING THE FIRST APP
1.1 Installing Fluent NHibernate
Open Visual Studio , open the File menu, go to the New and Project submenus. In the window that opens, select ASP.NET MVC 4 (If .Net Framework 4 Versions is selected). Enter the name “BibliotecaTutor” and select the type “Basic”. (Next, I will abbreviate writing File-> New-> Project , and RClick - the right button)

Next, run Nuget Package ( Tools-> Library Package Manager-> Package Manager Console ). We write the following line: Install-Package FluentNHibernate . Press Enter, and wait for the installation of FluentNHibernat to complete.

If you need to install a specific version of FluentNhibernate, then look for a line on the NuGet website www.nuget.org/packages/FluentNHibernate/2.0.1 in the Version table.
1.2 Configuring FluentNHibernate
1.3 Links, Classes, Mappings
The following tables will be created in the project: Book, Author, Genre, Series and Mind.

1.3.1
One-to-one relationships - to any instance of entity A there corresponds only one instance of entity B, and vice versa. Example, Book and Mind tables . If I wrote a review of the book Metro 2033, then I cannot apply the exact same review of the book Metro 2034, and my review of the book Metro 2034 is not suitable for Metro 2033.
One-to-one communication is rarely used, since all this data can be successfully placed in one table. It is used in those cases if for some reason you want to divide one table into two tables. For example, those fields that are often empty, I put in a separate table.
One-to-many / many-to-one - to any instance of entity A there corresponds 0, 1 or several instances of entity B, but to any instance of entity B there is only one instance of entity A. Example of Book and Series . There can be many books in one series / cycle, but the book itself can be included in only one series / cycle.
What is the difference between one-to-many and many-to-one relationships? The same as between the phrases “student portfolio” and “student portfolio”. That is, it is important who in the relationship of the two objects is the main one - the student or portfolio.
Many-to-many- any instance of entity A corresponds to 0, 1 or more instances of entity B, and any instance of entity B corresponds to 0, 1 or more instances of entity A. Example Book and Author , Book and Genre . Several authors work on one book, for example, an anthology, but an author may have several books. These tables are linked together using staging tables such as Book_Author and Book_Genre .
1.3.2 Book Class and its Mapping
Let's create a simple application that will display data on a book on a web page stored in a SQL Server database. We fill in the Book class and create a mapping class for it.
What is mapping for? With its help, we connect the data of the Book class with the Book table (which will be created a little later), change the column names, determine the types of relationships, and so on.
After creating the Book Model, create a controller ( Controller-> RClick-> Add-> Controller ) and call it HomeController . We write a code that displays all the books from the Book table .
Next, create a strongly typed view (View) in which we display all the entries from the books. (RClick on the red caption View (book) -> Add View ). We check the boxes and select the following parameters, as in the figure below (so that in the Model Class you can select the Model Book from the list, build the Build-> Build Solution project ).

An automatically generated code is displayed in which all fields of the Book class are displayed . After creating the view, run the project (F5). A blank page is displayed.
But if you open SQL Server Manager Studio and look in the Biblioteca database , then the Book table will appear there. Fill it with data.

(You can change the columns, for example, Make Description from nVarChar (255) to text or NVarChar (Max)).

After that, refresh the page, which will look like the image below.

For a quick introduction to the simple CRUD operation with NHibernate and MVC, I recommend reading the following article in English: www.dotnetjalps.com/2014/07/fluent-nhibernate-asp-net-mvc-crud.html .
Also useful articles can be found here:github.com/jagregory/fluent-nhibernate/wiki/Getting-started (Eng); and its translation: habrahabr.ru/post/125135 .
More links in Russian: slynetblog.blogspot.com/2009/10/nhibernate-1.html
Table of Contents
Part 1. Launching the first application
Part 2. Creating classes, mapping and populating the database
1. STARTING THE FIRST APP
1.1 Installing Fluent NHibernate
Open Visual Studio , open the File menu, go to the New and Project submenus. In the window that opens, select ASP.NET MVC 4 (If .Net Framework 4 Versions is selected). Enter the name “BibliotecaTutor” and select the type “Basic”. (Next, I will abbreviate writing File-> New-> Project , and RClick - the right button)

Next, run Nuget Package ( Tools-> Library Package Manager-> Package Manager Console ). We write the following line: Install-Package FluentNHibernate . Press Enter, and wait for the installation of FluentNHibernat to complete.

If you need to install a specific version of FluentNhibernate, then look for a line on the NuGet website www.nuget.org/packages/FluentNHibernate/2.0.1 in the Version table.
1.2 Configuring FluentNHibernate
- Open the SQL Server Manager database and create the Biblioteca database there
- Open Visual Studio, in the “Models” folder, create the class “Book.cs” (Models-> Book.cs)
- Create the NHibernate folder in Models and add the NHibernateHelper.cs class there ( Models-> NHibernate-> NHibernateHelper.cs )
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
public class NHibernateHelper {
public static ISession OpenSession() {
ISessionFactory sessionFactory = Fluently.Configure()
//Настройки БД. Строка подключения к БД MS Sql Server 2008
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(@"Server=..\SQLENTERPRISE; initial catalog= Biblioteca; Integrated Security=SSPI;")
.ShowSql()
)
//Маппинг. Используя AddFromAssemblyOf NHibernate будет пытаться маппить КАЖДЫЙ класс в этой сборке (assembly). Можно выбрать любой класс.
.Mappings(m =>m.FluentMappings.AddFromAssemblyOf())
//SchemeUpdate позволяет создавать/обновлять в БД таблицы и поля (2 поле ==true)
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true))
.BuildSessionFactory();
return sessionFactory.OpenSession();
}
}
1.3 Links, Classes, Mappings
The following tables will be created in the project: Book, Author, Genre, Series and Mind.

1.3.1
One-to-one relationships - to any instance of entity A there corresponds only one instance of entity B, and vice versa. Example, Book and Mind tables . If I wrote a review of the book Metro 2033, then I cannot apply the exact same review of the book Metro 2034, and my review of the book Metro 2034 is not suitable for Metro 2033.
One-to-one communication is rarely used, since all this data can be successfully placed in one table. It is used in those cases if for some reason you want to divide one table into two tables. For example, those fields that are often empty, I put in a separate table.
One-to-many / many-to-one - to any instance of entity A there corresponds 0, 1 or several instances of entity B, but to any instance of entity B there is only one instance of entity A. Example of Book and Series . There can be many books in one series / cycle, but the book itself can be included in only one series / cycle.
What is the difference between one-to-many and many-to-one relationships? The same as between the phrases “student portfolio” and “student portfolio”. That is, it is important who in the relationship of the two objects is the main one - the student or portfolio.
Many-to-many- any instance of entity A corresponds to 0, 1 or more instances of entity B, and any instance of entity B corresponds to 0, 1 or more instances of entity A. Example Book and Author , Book and Genre . Several authors work on one book, for example, an anthology, but an author may have several books. These tables are linked together using staging tables such as Book_Author and Book_Genre .
1.3.2 Book Class and its Mapping
Let's create a simple application that will display data on a book on a web page stored in a SQL Server database. We fill in the Book class and create a mapping class for it.
using System;
using FluentNHibernate.Mapping;
namespace BibliotecaTutor.Models {
public class Book {
public virtual int Id { get; set; }
//Название
public virtual string Name { get; set; }
//Описание
public virtual string Description { get; set; }
//Оценка Мира фантастики
public virtual int MfRaiting { get; set; }
////Номера страниц
public virtual int PageNumber { get; set; }
//Ссылка на картинку
public virtual string Image { get; set; }
//Дата поступления книги (фильтр по новикам!)
public virtual DateTime IncomeDate { get; set; }
}
//Маппинг класса
public class BookMap : ClassMap {
public BookMap() {
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.Description);
Map(x => x.MfRaiting);
Map(x => x.PageNumber);
Map(x => x.Image);
Map(x => x.IncomeDate);
}
}
}
What is mapping for? With its help, we connect the data of the Book class with the Book table (which will be created a little later), change the column names, determine the types of relationships, and so on.
After creating the Book Model, create a controller ( Controller-> RClick-> Add-> Controller ) and call it HomeController . We write a code that displays all the books from the Book table .
public ActionResult Index()
{
using (ISession session = NHibernateHelper.OpenSession()) {
book = session.Query().ToList()
return View(book);
}
}
Next, create a strongly typed view (View) in which we display all the entries from the books. (RClick on the red caption View (book) -> Add View ). We check the boxes and select the following parameters, as in the figure below (so that in the Model Class you can select the Model Book from the list, build the Build-> Build Solution project ).

An automatically generated code is displayed in which all fields of the Book class are displayed . After creating the view, run the project (F5). A blank page is displayed.
But if you open SQL Server Manager Studio and look in the Biblioteca database , then the Book table will appear there. Fill it with data.

(You can change the columns, for example, Make Description from nVarChar (255) to text or NVarChar (Max)).

After that, refresh the page, which will look like the image below.
