Skip to main content

Fluent Nhibernate : Create Table from Code(Class- CodeFirst)

Now days,  Convention over configured is more preferred and that’s why Fluent Nhibernate got more popularity Because with Fluent Nhibernate we don’t have to write and maintain mapping in xml. You can write classes to map your domain objects to your database tables. If you want to learn how we can do this with existing database and Fluent Nhibernate, I have also written a blog post about CRUD operation with Fluent Nhibernate and ASP.NET MVC . After writing this blog post I was getting a lots of emails about how we can create database from the Fluent Nhibernate as we can do same with Entity Framework Code First. So I thought it’s a good idea to write a blog post about it instead of writing individual emails.

How to create tables from class via Fluent Nhibernate:

To Demonstrate how we can create tables based mapping classes create we’re going to create a console application via adding new project like below.


console-application-fluent-nhibernate-code-first

Once you are done with creating application. It’s time to add reference for Fluent Nhibernate. You can do this via your library package manager like following.

adding-package-fluent-nhibernate

Now once, done with adding Fluent Nhibernate code, I have created a simple class “Customer” like below.
namespace FluentNhibernateCodeFirst
{
    public class Customer
    {
        public virtual int CustomerId { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
    } 
}
Here you can see I have created three properties which will be also column of our database table. Now as we know we need to write a mapping class for customer so below is my customer map class.
using FluentNHibernate.Mapping;

namespace FluentNhibernateCodeFirst
{
    public class CustomerMap : ClassMap<Customer>
    {
        public CustomerMap()
        {
            Id(c => c.CustomerId);
            Map(c => c.FirstName);
            Map(c => c.LastName);
        }
    }
}
Here, I map ID  Customer Id as customer Id will be primary key. Now it’s time to write code creating database and saving some data into customer table created.
using System;
using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace FluentNhibernateCodeFirst
{
    class Program
    {
        private static ISessionFactory _sessionFactory;

        static void Main(string[] args)
        {
            //creating database 
            string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
            CreateDatabase(connectionString);
            Console.WriteLine("Database Created sucessfully");

            //creating a object of customer
            Customer customer=new Customer
            {
                CustomerId = 1,
                FirstName = "Jalpesh",
                LastName = "Vadgama"
            };

            //saving customer in database.
            using(ISession session = _sessionFactory.OpenSession())
                session.Save(customer);

            Console.WriteLine("Customer Saved");

        }

        static void CreateDatabase(string connectionString)
        {
            var configuration = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString).ShowSql)
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMap>())
                .BuildConfiguration();

            var exporter = new SchemaExport(configuration);   
            exporter.Execute(true, true, false);

            _sessionFactory = configuration.BuildSessionFactory();  
        }
    }

    
}
Here in the above code, If you above code care fully then, I have created function called CreateDatabase. In this function First it will create a mapping and then that schema mapping will be executed against database to create table.

After creating table, I have initialize the customer object and saved it into database. Now when you run this application. You will get output like below as expected.

fluent-nhibernate-code-first-nhibernate

And now if you see database in the SQL Management Studio, Customer table has created like below.

customer-table-created-fluent-nhibernate

And If you see that table, Data is also inserted like below.

data-inserted-fluent-nhibernate

That’s it. Hope you like it. Stay tuned for more!.

You can find complete sourcecode of this example at github on -https://github.com/dotnetjalps/FluentHinbernateCodeFirst

Comments

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command How to solve : gulp is not recognized as internal or external command To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.



Go to Advance System Settings and it will open system properties windows like below.



Click on Environment Variables it will open an environment and system variables windows like below.



Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.



Click on Ok. That’s it. N…