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=520;").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);
}

  

Fluent Nhibernate and Stored Procedures的更多相关文章

  1. 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)

    在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...

  2. Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one SQL statement

    Is there any way in which I can clean a database in SQl Server 2005 by dropping all the tables and d ...

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

    英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs ...

  4. 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 fol ...

  5. Fluent Nhibernate之旅(五)--利用AutoMapping进行简单开发

    Fluent Nhibernate(以下简称FN)发展到如今,已经相当成熟了,在Nhibernate的书中也相应的推荐了使用FN来进行映射配置,之前写的FN之旅至今还有很多人会来私信我问题,说来惭愧, ...

  6. [Fluent NHibernate]第一个程序

    目录 写在前面 Fluent Nhibernate简介 基本配置 总结 写在前面 在耗时两月,NHibernate系列出炉这篇文章中,很多园友说了Fluent Nhibernate的东东,也激起我的兴 ...

  7. [Fluent NHibernate]一对多关系处理

    目录 写在前面 系列文章 一对多关系 总结 写在前面 上篇文章简单介绍了,Fluent Nhibernate使用代码的方式生成Nhibernate的配置文件,以及如何生成持久化类的映射文件.通过上篇的 ...

  8. [MySQL] Stored Procedures 【转载】

    Stored routines (procedures and functions) can be particularly useful in certain situations: When mu ...

  9. Good Practices to Write Stored Procedures in SQL Server

    Reference to: http://www.c-sharpcorner.com/UploadFile/skumaar_mca/good-practices-to-write-the-stored ...

随机推荐

  1. iOS 10.0 更新点(开发者视角)

    html, body {overflow-x: initial !important;}html { font-size: 14px; } body { margin: 0px; padding: 0 ...

  2. [译] 一、为何要推出AppCoda系列?

    声明:本文翻译自AppCoda网站的文章:Why Launching AppCoda?,作者是创建者Simon Ng.如有异议,请联系博主. 去年九月份,我在App Store上发布了自己第一个iPh ...

  3. [转载] linux下打开windows txt文件中文乱码问题

    原文链接 在linux操作系统下,我们有时打开在windows下的txt文件,发现在windows下能正常显示的txt文件出现了中文乱码. 出现这种情况的原因为两种操作系统的中文压缩方式不同,在win ...

  4. OpenSSL Command-Line HOWTO

    OpenSSL Command-Line HOWTO The openssl application that ships with the OpenSSL libraries can perform ...

  5. css3整理--clip

    clip语法: .selector { clip: rect | auto | inherit } 注意:clip属性只能在元素设置了“position:absolute”或者“position:fi ...

  6. SSAS:OLE DB 错误: OLE DB 或 ODBC 错误 : Login failed for user 'NT Service\MSSQLServerOLAPService'

    问题描述 按照微软官方教程尝试使用SSAS做OLAP时,出现如下错误信息: Severity Code Description Project File Line Suppression State ...

  7. java之接口interface

    接口 1.多个无关的类可以实现同一个接口 2.一个类可以实现多个无关的接口 3.与继承关系类似,接口与实现类之间存在多态性 4.定义java类的语法格式 < modifier> class ...

  8. git clone简介

    翻译整理自: http://web.mit.edu/~mkgray/project/silk/root/afs/sipb/project/git/git-doc/git-clone.html  在使用 ...

  9. CentOS安装epel

    Centos5安装    rpm -ivh http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm   rpm  ...

  10. Query Object--查询对象模式(上)

    回顾 上两篇文章主要讲解了我对于数据层的Unit Of Work(工作单元模式)的理解,其中包括了CUD的操作,那么今天就来谈谈R吧,文章包括以下几点: 什么是Query Object 基于SQL的实 ...