Fluent Nhibernate and Stored Procedures

sql:存储过程

DROP TABLE Department
GO
CREATE TABLE Department
(
	Id  INT IDENTITY(1,1) PRIMARY KEY,
	DepName VARCHAR(50),
	PhoneNumber VARCHAR(50)
)
GO

CREATE PROCEDURE [dbo].[GetDepartmentId]
 ( @Id INT )
AS
    BEGIN
        SELECT  *
        FROM    Department

        WHERE   Department.Id= @Id
    END
GO

EXEC GetDepartmentId 1
GO

  

 /// <summary>
        /// 存储过程
        /// </summary>
        /// <returns></returns>
        static ISessionFactory testSession()
        {
           // var config = MsSqlConfiguration.MsSql2005.ConnectionString(@"Server=LF-WEN\GEOVINDU;initial catalog=NHibernateSimpleDemo;User ID=sa;Password=520;").ShowSql();
           // var db = Fluently.Configure()
           //     .Database(config)
           //     .Mappings(a =>
           //     {
           //         a.FluentMappings.AddFromAssemblyOf<Form1>();
           //         a.HbmMappings.AddClasses(typeof(Department));
           //     });
           // db.BuildConfiguration();
           //return db.BuildSessionFactory();

            ISessionFactory isessionFactory = Fluently.Configure()
               .Database(MsSqlConfiguration.MsSql2005
               .ConnectionString(@"Server=GEOVINDU-PC\GEOVIN;initial catalog=NHibernateSimpleDemo;User ID=sa;Password=770214;").ShowSql())
                            .Mappings(m => m
                            //.FluentMappings.PersistenceModel
                            //.FluentMappings.AddFromAssembly();
                            .FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())) //用法注意
               //.Mappings(m => m
               //.FluentMappings.AddFromAssemblyOf<Form1>())
               //.Mappings(m => m
               //.HbmMappings.AddFromAssemblyOf<Department>())
               //.BuildConfiguration()
               .BuildSessionFactory();
            return isessionFactory;
        }

        /// <summary>
        /// 存储过程 涂聚文测试成功。 WIN7
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                using (var exc = testSession())
                {
                    using (var st = exc.OpenSession())
                    {
                        if (!object.Equals(st, null))
                        {
                            //1
                            string sql = @"exec GetDepartmentId @Id=:Id";// @"exec GetDepartmentId :Id";
                            IQuery query = st.CreateSQLQuery(sql)  //CreateSQLQuery(sql) //GetNamedQuery("GetDepartmentId")
                                //.SetInt32("Id", 1)
                                   .SetParameter("Id", 1)
                                   .SetResultTransformer(
                                    Transformers.AliasToBean(typeof(Department)));
                                    //.List<Department>(); 

                            var clients = query.UniqueResult();// query.List<Department>().ToList(); //不能强制转化

                            //IList<Department> result = query.List<Department>(); //不是泛值中的集合
                            Department dep=new Department();
                            dep = (Department)clients; //无法将类型为“System.Object[]”的对象强制转换为类型
                            //2
                            //var clients = st.GetNamedQuery("GetDepartmentId")
                            //        .SetParameter("Id", 1)
                            //        .SetResultTransformer(Transformers.AliasToBean(typeof(Department)))
                            //        .List<Department>().ToList();
                            MessageBox.Show(dep.DepName);
                        }
                    }
                }

  参考:http://stackoverflow.com/questions/6373110/nhibernate-use-stored-procedure-or-mapping

/// <summary>
        /// Activation
        ///
        /// Action
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IEnumerable<Department> GetDeactivationList(int companyId)
        {
            var sessionFactory = FluentNHibernateHelper.CreateSessionFactory();// BuildSessionFactory();
            var executor = new HibernateStoredProcedureExecutor(sessionFactory);
            var deactivations = executor.ExecuteStoredProcedure<Department>(
              "GetDepartmentId",
              new[]
              {
                  new SqlParameter("Id", companyId),
                  //new SqlParameter("startDate", startDate),
                 // new SqlParameter("endDate", endDate),
              });

            return deactivations;
        }

  

 /// <summary>
    /// 存储过程操作
    /// </summary>
    public class HibernateStoredProcedureExecutor : IExecuteStoredProcedure
    {

        /// <summary>
        ///
        /// </summary>
        private readonly ISessionFactory _sessionFactory;
        /// <summary>
        ///
        /// </summary>
        /// <param name="sessionFactory"></param>
        public HibernateStoredProcedureExecutor(ISessionFactory sessionFactory)
        {
            sessionFactory = FluentNHibernateHelper.CreateSessionFactory();
            _sessionFactory = sessionFactory;
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TOut"></typeparam>
        /// <param name="procedureName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public IEnumerable<TOut> ExecuteStoredProcedure<TOut>(string procedureName, IList<SqlParameter> parameters)
        {
            IEnumerable<TOut> result;

            using (var session = _sessionFactory.OpenSession())
            {
                var query = session.GetNamedQuery(procedureName);
                AddStoredProcedureParameters(query, parameters);
                result = query.List<TOut>();
            }

            return result;
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TOut"></typeparam>
        /// <param name="procedureName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public TOut ExecuteScalarStoredProcedure<TOut>(string procedureName, IList<SqlParameter> parameters)
        {
            TOut result;

            using (var session = _sessionFactory.OpenSession())
            {
                var query = session.GetNamedQuery(procedureName);
                AddStoredProcedureParameters(query, parameters);
                result = query.SetResultTransformer(Transformers.AliasToBean(typeof(TOut))).UniqueResult<TOut>();
            }

            return result;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IQuery AddStoredProcedureParameters(IQuery query, IEnumerable<SqlParameter> parameters)
        {
            foreach (var parameter in parameters)
            {
                query.SetParameter(parameter.ParameterName, parameter.Value);
            }

            return query;
        }
    }
    /// <summary>
    ///
    /// </summary>
    public interface IExecuteStoredProcedure
    {
        TOut ExecuteScalarStoredProcedure<TOut>(string procedureName, IList<SqlParameter> sqlParameters);
        IEnumerable<TOut> ExecuteStoredProcedure<TOut>(string procedureName, IList<SqlParameter> sqlParameters);
    }

  

时间: 2024-11-18 02:27:04

Fluent Nhibernate and Stored Procedures的相关文章

[Fluent NHibernate]第一个程序

目录 写在前面 Fluent Nhibernate简介 基本配置 总结 写在前面 在耗时两月,NHibernate系列出炉这篇文章中,很多园友说了Fluent Nhibernate的东东,也激起我的兴趣,想对它一探究竟,这里也将Fluent Nhibernate写成一个系列,记录自己的学习过程,关于这东东,也是第一次接触,也只能边摸索,边记录了.如果有描述错误的地方,还望多多包涵. 通过Nhibernate的学习,都觉得Nhibernate的使用映射文件的编写很麻烦,这里通过Fluent Nhi

Fluent NHibernate and Mysql,SQLite

http://codeofrob.com/entries/sqlite-csharp-and-nhibernate.html https://code.google.com/archive/p/csharp-sqlite/downloads https://github.com/davybrion/NHibernateWorkshop MySQL /// <summary> ///MySQL 创建ISessionFactory /// </summary> /// <retu

An Introduction to Stored Procedures in MySQL 5

https://code.tutsplus.com/articles/an-introduction-to-stored-procedures-in-mysql-5--net-17843 MySQL 5 introduced a plethora of new features - stored procedures being one of the most significant. In this tutorial, we will focus on what they are, and h

关于Natively Compiled Stored Procedures的优化

Interpreted Transact-SQL stored procedures are compiled at first execution, in contrast to natively compiled stored procedures, which are compiled at create time. When interpreted stored procedures are compiled at invocation, the values of the parame

MySQL Error Handling in Stored Procedures 2

Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in stored procedures. When an error occurs inside a stored procedure, it is important to handle it appropriately, such as continuing or exiting the c

Home / Python MySQL Tutorial / Calling MySQL Stored Procedures in Python Calling MySQL Stored Procedures in Python

f you are not familiar with MySQL stored procedures or want to review it as a refresher, you can follow the MySQL stored procedures tutorial. We will create two stored procedures for the demonstration in this tutorial. The first stored procedure gets

[Fluent NHibernate]一对多关系处理

目录 写在前面 系列文章 一对多关系 总结 写在前面 上篇文章简单介绍了,Fluent Nhibernate使用代码的方式生成Nhibernate的配置文件,以及如何生成持久化类的映射文件.通过上篇的学习你会发现,Fluent Nhibernate仍然需要引用Nhibernate的两个程序集(Nhibernate.dll和Iesi.Collections.dll),所以与Nhibernate最大的区别就在生成配置文件的方式上面,这里关于Nhibernate的特性方面就不再多赘述,可以参考Nhib

Fluent NHibernate and Spring.net

http://blog.bennymichielsen.be/2009/01/04/using-fluent-nhibernate-in-spring-net/ http://comments.gmane.org/gmane.comp.windows.dotnet.nhibernate.user.general/21840 http://codegur.com/2049968/configuring-asp-net-mvc-2-with-spring-net-and-fluentnhiberna

【翻译】Fluent NHibernate介绍和入门指南

英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs.com/13yan/p/5685307.html 入门指南 Fluent NHibernate 概述 Fluent NHibernate 提供一个替代 NHibernate 的标准 XML 映射文件的方法.而不是编写 XML 文档 (.hbm.xml 文件),Fluent NHibernate 可