DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Work With Fluent NHibernate in Core 2.0
  • A New Era Has Come, and So Must Your Database Observability
  • Conversational Applications With Large Language Models Understanding the Sequence of User Inputs, Prompts, and Responses
  • Automating Database Operations With Ansible and DbVisualizer

Trending

  • TDD With FastAPI Is Easy
  • Multi-Tenancy With Keycloak, Angular, and SpringBoot
  • Running End-To-End Tests in GitHub Actions
  • How to Configure Istio, Prometheus and Grafana for Monitoring
  1. DZone
  2. Data Engineering
  3. Databases
  4. Fluent Nhibernate: Create Table from Code(Class- CodeFirst)

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

Jalpesh Vadgama user avatar by
Jalpesh Vadgama
·
Mar. 30, 15 · Interview
Like (3)
Save
Tweet
Share
20.10K Views

Join the DZone community and get the full member experience.

Join For Free

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 an 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 lot of emails about how we can create database from the Fluent Nhibernate, as we can do the same with Entity Framework Code First. So I thought it was 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
Database NHibernate

Published at DZone with permission of Jalpesh Vadgama, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Work With Fluent NHibernate in Core 2.0
  • A New Era Has Come, and So Must Your Database Observability
  • Conversational Applications With Large Language Models Understanding the Sequence of User Inputs, Prompts, and Responses
  • Automating Database Operations With Ansible and DbVisualizer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: