Fluent NHibernate example

来源:http://www.cnblogs.com/geovindu/archive/2016/03/27/5325765.html
-Advertisement-
Play Games

http://www.codeproject.com/Articles/26466/Dependency-Injection-using-Spring-NET http://stackoverflow.com/questions/29767825/spring-netnhibernate-confi ...


http://www.codeproject.com/Articles/26466/Dependency-Injection-using-Spring-NET

http://stackoverflow.com/questions/29767825/spring-netnhibernate-configuration

http://nhbusinessobj.sourceforge.net/index.html

 http://code.google.com/p/genericrepository/

sql:

CREATE TABLE [dbo].[Customers](
[customer_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[name] [nvarchar](75) NULL,
[email] [nvarchar](95) NULL,
[contact_person] [nvarchar](75) NULL,
[postal_address] [nvarchar](150) NULL,
[physical_address] [nvarchar](150) NULL,
[contact_number] [nvarchar](50) NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[customer_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
 
INSERT INTO [dbo].[Customers]
           ([name]
           ,[email]
           ,[contact_person]
           ,[postal_address]
           ,[physical_address]
           ,[contact_number])
     VALUES
           ('Kode Blog'
           ,'[email protected]'
           ,'Rodrick Kazembe'
           ,'Private Bag WWW'
           ,'Tanzania'
           ,'911')
   INSERT INTO [dbo].[Customers]
           ([name]
           ,[email]
           ,[contact_person]
           ,[postal_address]
           ,[physical_address]
           ,[contact_number])
     VALUES       
   ('Google Inc'
           ,'[email protected]'
           ,''
           ,''
           ,'USA'
           ,'')
GO

  

    /// <summary>
    /// 
    /// </summary>
    public class Customers
    {
        public virtual int customer_id { get; protected set; }
        public virtual string name { get; set; }
        public virtual string email { get; set; }
        public virtual string contact_person { get; set; }
        public virtual string postal_address { get; set; }
        public virtual string physical_address { get; set; }
        public virtual string contact_number { get; set; }
    }

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Mapping;


namespace CodeBlogdeom
{
    /// <summary>
    /// 
    /// </summary>
    class CustomersMap : ClassMap<Customers>
    {
        /// <summary>
        /// 
        /// </summary>
        public CustomersMap()
        {
            Id(x => x.customer_id);
            Map(x => x.name);
            Map(x => x.email);
            Map(x => x.contact_person);
            Map(x => x.postal_address);
            Map(x => x.physical_address);
            Map(x => x.contact_number);
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using NHibernate.Persister;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
//http://www.kode-blog.com/2014/04/fluent-nhibernate-tutorial-c-windows-crud-example/

namespace CodeBlogdeom
{

    /// <summary>
    /// 
    /// </summary>
    public partial class frmCustomers : Form
    {

        #region declarations
        ISessionFactory sessionFactory;
        #endregion

        #region methods
        private void load_records(string sFilter = "")
        {
            try
            {
                sessionFactory = CreateSessionFactory();

                using (var session = sessionFactory.OpenSession())
                {
                    string h_stmt = "FROM Customers";

                    if (sFilter != "")
                    {
                        h_stmt += " WHERE " + sFilter;
                    }
                    IQuery query = session.CreateQuery(h_stmt);

                    IList<Customers> customersList = query.List<Customers>();

                    dgvListCustomers.DataSource = customersList;

                    lblStatistics.Text = "Total records returned: " + customersList.Count;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            ISessionFactory isessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005
                .ConnectionString(@"Server=GEOVINDU-PC\GEOVIN; Database=NHibernateSimpleDemo; Integrated Security=SSPI;"))
                .Mappings(m => m
                .FluentMappings.AddFromAssemblyOf<frmCustomers>())
                .BuildSessionFactory();

            return isessionFactory;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="customer_id"></param>
        private void load_customer_details(int customer_id)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        IQuery query = session.CreateQuery("FROM Customers WHERE customer_id = " + customer_id);

                        Customers customer = query.List<Customers>()[0];

                        txtCustomerId.Text = customer.customer_id.ToString();
                        txtName.Text = customer.name;
                        txtEmail.Text = customer.email;
                        txtContactPerson.Text = customer.contact_person;
                        txtContactNumber.Text = customer.contact_number;
                        txtPostalAddress.Text = customer.postal_address;
                        txtPhysicalAddress.Text = customer.physical_address;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Exception Msg");
                    }
                }
            }
        }

        #endregion
        /// <summary>
        /// 
        /// </summary>
        public frmCustomers()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            load_records();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFilter_Click(object sender, EventArgs e)
        {
            string sFilterValue = string.Empty;
            string sField = cboFilter.Text;
            string sCriteria = cboCriteria.Text;
            string sValue = txtValue.Text;

            switch (sCriteria)
            {
                case "Equals":
                    sFilterValue = sField + " = '" + sValue + "'";
                    break;

                case "Begins with":
                    sFilterValue = sField + " LIKE '" + sValue + "%'";
                    break;

                case "Contains":
                    sFilterValue = sField + " LIKE '%" + sValue + "%'";
                    break;

                case "Ends with":
                    sFilterValue = sField + " LIKE '%" + sValue + "'";
                    break;
            }

            //data.Add(sFilterValue, sValue);

            load_records(sFilterValue);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvListCustomers_Click(object sender, EventArgs e)
        {
            int customer_id = 0;

            customer_id = int.Parse(dgvListCustomers.CurrentRow.Cells[0].Value.ToString());

            load_customer_details(customer_id);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddNew_Click(object sender, EventArgs e)
        {
            //data validation
            if (txtName.Text == "")
            {
                MessageBox.Show("The name field is required", "Null name", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            if (txtEmail.Text == "")
            {
                MessageBox.Show("The email field is required", "Null email", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            if (txtPhysicalAddress.Text == "")
            {
                MessageBox.Show("The physical address field is required", "Null physical address", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            Customers customer = new Customers();

            customer.name = txtName.Text;
            customer.email = txtEmail.Text;
            customer.contact_person = txtContactPerson.Text;
            customer.contact_number = txtContactNumber.Text;
            customer.physical_address = txtPhysicalAddress.Text;
            customer.postal_address = txtPostalAddress.Text;

            using (var session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(customer);

                        transaction.Commit();

                        load_records();
                    }

                    catch (Exception ex)
                    {
                        transaction.Rollback();

                        MessageBox.Show(ex.Message, "Exception Msg");
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            load_records();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            //data validation
            if (txtName.Text == "")
            {
                MessageBox.Show("The name field is required", "Null name", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            if (txtEmail.Text == "")
            {
                MessageBox.Show("The email field is required", "Null email", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            if (txtPhysicalAddress.Text == "")
            {
                MessageBox.Show("The physical address field is required", "Null physical address", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            using (var session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        IQuery query = session.CreateQuery("FROM Customers WHERE customer_id = '" + txtCustomerId.Text + "'");

                        Customers customer = query.List<Customers>()[0];

                        customer.name = txtName.Text;
                        customer.email = txtEmail.Text;
                        customer.contact_person = txtContactPerson.Text;
                        customer.contact_number = txtContactNumber.Text;
                        customer.physical_address = txtPhysicalAddress.Text;
                        customer.postal_address = txtPostalAddress.Text;

                        session.Update(customer);

                        transaction.Commit();

                        load_records();
                    }

                    catch (Exception ex)
                    {
                        transaction.Rollback();

                        MessageBox.Show(ex.Message, "Exception Msg");
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            using (ISession session = sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        IQuery query = session.CreateQuery("FROM Customers WHERE customer_id = '" + txtCustomerId.Text + "'");
 
                        Customers customer = query.List<Customers>()[0];
 
                        session.Delete(customer); //delete the record
 
                        transaction.Commit(); //commit it
 
                        btnRefresh_Click(sender, e);
 
                    }
 
                    catch (Exception ex)
                    {
 
                        transaction.Rollback();
 
                        MessageBox.Show(ex.Message, "Exception Msg");
 
                    }
 
                }
 
            }
       
        }
    }
}

http://blog.csdn.net/zhang_xinxiu/article/details/42131907  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 難點主要在參數的傳遞方式吧,不過查資料後發現很簡單。 1.使用-e參數傳遞命令,適用於簡單語句 mysql -uuser -ppasswd -e "create database dbtest;" 2.使用EOF傳遞複雜語句 mysql -uuser -ppasswd <<EOF create da ...
  • 一、變數的顯示與設置 1、變數的顯示運用echo命令 +$符號: 上圖例子顯示的是系統變數,咱們可以自己設置變數 2、設置變數運用“=”符號 設置了變數NIU 值為“niunai” 變數設置規則: (1)等號兩邊不能有空格的出現 (2)變數只能是數字和字母的組合,但數字不能在前面 (3)變數值可以用... ...
  • 今天要查看伺服器和TUTK版本,看了一下資料: 新接手了幾台linux的伺服器,第一步當然是要瞭解這些伺服器的軟硬體配置.現在就寫出我這次用的一些命令. 首先當然要取得機器的IP,用戶名和密碼(呵呵,不知道就找原來的管理員要哈) 登陸之後,首先看到的就是機器的名稱,一般提示符就有了,如 [root@ ...
  • 破解的目的是將受限的個人版變為全功能的Pro版,破解後就可以使用所有功能了,界面也變成了黑色的主題。 破解網址(支持最新版的5.3.4f1): http://www.ceeger.com/forum/read.php?tid=23396&page=1 已測試破解沒有問題。 ...
  • 今天真是個鬱悶的日子,因為老師兩個星期前給我的一個任務,用遞歸演算法將Oracle資料庫中用戶信息及許可權顯示在jquery-treeView上,網上雖然有大神寫出了這類演算法,但是不貼全部代碼,真的很難跟著寫出來啊(或者本人能力有限),今天和老師爭論了一下午,老師都差點懷疑我能力有問題了,雖然我確實能力 ...
  • 一、Memcached是什麼? Memcached是一個高性能的分散式記憶體對象緩存系統,可以在記憶體中緩存數據和對象來減少讀取資料庫的次數,從而提醒性能。Memcached基於一個K/V對的hashmap。 二、Memcached的特征 1. 協議簡單:基於文本協議和二進位協議進行通信 2. 基於li ...
  • 廣州傳智博客黑馬訓練營.Net15期 7 張揚波 MVC大項目6 張揚波 MVC3 胡凌浩 HTML&JS2 基礎加強+三層 5 張揚波 企業站點(asp.net)&EF 4 江佳恆 ASP.net 1 王絢文 dotnet基礎下載地址:http://fu83.cn/thread-24-1-1.ht ...
  • 寫ASP.NET MVC程式,我們經常需要把數據從視圖(View)傳遞至部分視圖(Partial View) 或者相反。今天Insus.NET使用 ControllerBase.TempData 進行處理。 首先演示的是View至Parital View創建一個控制器,並添加一個操作TmTestA( ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...