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> /// 存储过程 /// </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); } } }