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 ...
随机推荐
- WCF实例上下文模式与并发模式对性能的影响
实例上下文模式 InstanceContextMode 控制在响应客户端调用时,如何分配服务实例.InstanceContextMode 可以设置为以下值: •Single – 为所有客户端调用分配一 ...
- GPUImage 内置滤镜解析
#pragmamark - 调整颜色 Handle Color GPUImageBrightnessFilter //亮度GPUImageExposureFilter //曝光GPUImageCont ...
- HDU 4107 Gangster Segment Tree线段树
这道题也有点新意,就是须要记录最小值段和最大值段,然后成段更新这个段,而不用没点去更新,达到提快速度的目的. 本题过的人非常少,由于大部分都超时了,我严格依照线段树的方法去写.一開始竟然也超时. 然后 ...
- Kafka - SQL 代码实现
1.概述 上次给大家分享了关于 Kafka SQL 的实现思路,这次给大家分享如何实现 Kafka SQL.要实现 Kafka SQL,在上一篇<Kafka - SQL 引擎分享>中分享了 ...
- [原创]Andorid DexClassLoader的创建过程解析(基于5.0)
做Android插件框架时,经常会用到dex的动态加载,就要直接或间接的使用DexClassLoader,在new DexClassLoader的时候Android系统做了很多工作,下面我们详细分析一 ...
- WinStore控件之TextBlock
1 TextBlock简单实例应用 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}&quo ...
- 使用GROUP BY统计记录条数 COUNT(*) DISTINCT
例如这样一个表,我想统计email和passwords都不相同的记录的条数 CREATE TABLE IF NOT EXISTS `test_users` ( `email_id` ) unsigne ...
- CSS基础汇总
1. css的出现是为了是内容和表现分离.分为三种: 内联:不推荐 嵌入:没有利用浏览器缓存机制. 外联: 2. css优先级:①id优先级高于class②后面的样式覆盖前面的③指定的高于继承④行内样 ...
- 支付SDK的安全问题——隐式意图可导致钓鱼攻击
该漏洞涉及到app所使用的intent和intent filter. intent是一个可用于从一个app组件请求动作或处理事件的“消息对象”.Intent负责对应用中一次操作的动作.动作涉及数据. ...
- protobuf-net
protobuf是google的一个开源项目,可用于以下两种用途: (1)数据的存储(序列化和反序列化),类似于xml.json等: (2)制作网络通信协议. 源代码下载地址:https://gith ...