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=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的更多相关文章
- 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)
在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...
- 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 ...
- 【翻译】Fluent NHibernate介绍和入门指南
英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs ...
- 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 ...
- Fluent Nhibernate之旅(五)--利用AutoMapping进行简单开发
Fluent Nhibernate(以下简称FN)发展到如今,已经相当成熟了,在Nhibernate的书中也相应的推荐了使用FN来进行映射配置,之前写的FN之旅至今还有很多人会来私信我问题,说来惭愧, ...
- [Fluent NHibernate]第一个程序
目录 写在前面 Fluent Nhibernate简介 基本配置 总结 写在前面 在耗时两月,NHibernate系列出炉这篇文章中,很多园友说了Fluent Nhibernate的东东,也激起我的兴 ...
- [Fluent NHibernate]一对多关系处理
目录 写在前面 系列文章 一对多关系 总结 写在前面 上篇文章简单介绍了,Fluent Nhibernate使用代码的方式生成Nhibernate的配置文件,以及如何生成持久化类的映射文件.通过上篇的 ...
- [MySQL] Stored Procedures 【转载】
Stored routines (procedures and functions) can be particularly useful in certain situations: When mu ...
- 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 ...
随机推荐
- 【网络——Linux】——IPMI详细介绍【转】
一.IPMI含义 智能平台管理接口(IPMI:Intelligent Platform Management Interface)是一项应用于服务器管理系统设计的标准,由Intel.HP.Dell和N ...
- JSON处理
var ajax = function () { mui.ajax(projectPath+'/goods/goodsprice.do', { dataType: 'json', type: 'pos ...
- iis,w3wp一直出现WerFault.exe应用程序错误
这个进程是Windows错误报告技术里的一个东西,来收集软件崩溃或者挂起后的数据然后向微软反馈报告.关闭系统的错误报告功能后看看 1:打开 运行 (热键:win+R)输入 gpedit.msc 打开 ...
- 关于imp无法导出空表
前天在业务库中导出完整库时,再导入到新库时发现部分表丢失. 看日志后分析是部分空表没有导出.查google知,11G中新特性,当表无数据时,不分配segment,以节省空间.而使用exp命令时,无Se ...
- android中无限循环滑动的gallery实例
android中无限循环滑动的gallery实例 1.点击图片有变暗的效果,使用imageview.setAlpha(),并且添加ontouchListener public void init() ...
- saiku缓存整理
使用saiku的人,肯定都有这么一个经历,查询了一次多维分析数据表,第二次之后就特别快,因为它缓存了结果,可问题是过了一天,甚至几天,来源数据早都更换了,可还是这个缓存结果.问题来了,缓存不失效! 那 ...
- WPF常用控件样式集锦
1.不规则形状按钮(通过更改path实现) <Style x:Key="ButtonStyleForPath" TargetType="{x:Type Button ...
- WebDriver基本API使用(基于Java)V1.0
WebDriver基本API使用(基于Java)V1.0http://www.docin.com/p-803032877.html
- javascript 设计模式之观察者模式
观察者模式又叫发布——订阅模式,顾名思义pub——sub就是被动触发的,:不要给我......,我会给你.......就是一个发布订阅的解释,实质就是对程序中的某个对象状态进行监听观察,并且在该对象发 ...
- VMware三个版本workstation、server、esxi的区别
VMware三个版本 workstation: 单机级,用在个人桌面系统中,需要操作系统支持 servier:工作组级,用于服务器,需要操作系统支持 esxi:企业级,用于服务器,不需要操作系统支持 ...