Fluent NHibernate example
http://www.codeproject.com/Articles/26466/Dependency-Injection-using-Spring-NET
http://stackoverflow.com/questions/29767825/spring-netnhibernate-configuration
http://nhbusinessobj.sourceforge.net/index.html
http://code.google.com/p/genericrepository/
sql:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | CREATE TABLE [dbo].[Customers]( [customer_id] [ numeric ](18, 0) IDENTITY(1,1) NOT NULL , [ name ] [nvarchar](75) NULL , [email] [nvarchar](95) NULL , [contact_person] [nvarchar](75) NULL , [postal_address] [nvarchar](150) NULL , [physical_address] [nvarchar](150) NULL , [contact_number] [nvarchar](50) NULL , CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ( [customer_id] ASC ) WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ] ) ON [ PRIMARY ] GO INSERT INTO [dbo].[Customers] ([ name ] ,[email] ,[contact_person] ,[postal_address] ,[physical_address] ,[contact_number]) VALUES ( 'Kode Blog' , 'a-team@kode-blog.com' , 'Rodrick Kazembe' , 'Private Bag WWW' , 'Tanzania' , '911' ) INSERT INTO [dbo].[Customers] ([ name ] ,[email] ,[contact_person] ,[postal_address] ,[physical_address] ,[contact_number]) VALUES ( 'Google Inc' , 'info@google.com' , '' , '' , 'USA' , '' ) GO |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | ---- CREATE TABLE reader ( ReaderID varchar (20) NULL , ReaderName varchar (50) NULL , ReaderMaxCount INT NULL , Sex varchar (12) NULL , ReaderCode varchar (20) NULL , [ Password ] varchar (20) NULL ) GO INSERT INTO reader(ReaderID,ReaderName,ReaderMaxCount,Sex,ReaderCode,[ Password ]) VALUES ( '001' , 'geovindu' ,1, 'man' , '001' , '001' ) CREATE TABLE User1 ( [UId] UNIQUEIDENTIFIER DEFAULT (NEWID()) PRIMARY KEY , UName VARCHAR (50) NULL , UPwd VARCHAR (50) NULL , UAddress VARCHAR (50) NULL , ) GO INSERT INTO User1(UName,UPwd,UAddress) VALUES ( '001' , '001' , 'sz' ) GO SELECT * FROM user1 CREATE TABLE [ User ] ( Id INT IDENTITY(1,1) PRIMARY KEY , [ Name ] VARCHAR (50) NULL ) GO INSERT INTO [ User ]([ Name ]) VALUES ( 'geovindu' ) INSERT INTO [ User ]([ Name ]) VALUES ( 'sibodu' ) --- CREATE TABLE Users ( UserID INT IDENTITY(1,1) PRIMARY KEY , [ Name ] VARCHAR (50) NULL , [ No ] VARCHAR (50) NULL ) GO INSERT INTO Users([ Name ],[ NO ]) VALUES ( 'geovindu' , '001' ) INSERT INTO Users([ Name ],[ NO ]) VALUES ( 'sibodu' , '002' ) CREATE TABLE Projects ( ProjectID INT IDENTITY(1,1) PRIMARY KEY , [ Name ] VARCHAR (50) NULL , UserID INT FOREIGN KEY REFERENCES Users(UserID) ) GO INSERT INTO Projects([ Name ],UserID) VALUES ( '中考' ,1) INSERT INTO Projects([ Name ],UserID) VALUES ( '高考' ,1) INSERT INTO Projects([ Name ],UserID) VALUES ( '小考' ,2) CREATE TABLE UserDetails ( UserID INT FOREIGN KEY REFERENCES Users(UserID), Sex INT NULL , Age INT NULL , BirthDate DATETIME DEFAULT (GETDATE()), Height DECIMAL (6,2) DEFAULT (0) ) GO INSERT INTO UserDetails(UserID,Sex,Age,BirthDate,Height) VALUES (1,1,40, '1977-02-14' ,172.01) INSERT INTO UserDetails(UserID,Sex,Age,BirthDate,Height) VALUES (2,1,10, '2007-12-07' ,122.01) CREATE TABLE Product ( ProductID INT IDENTITY(1,1) PRIMARY KEY , [ Name ] VARCHAR (50) NULL , Color VARCHAR (50) NULL ) GO INSERT INTO Product([ Name ],Color) VALUES ( '电视机' , '黑色' ) INSERT INTO Product([ Name ],Color) VALUES ( '洗碗机' , '白色' ) INSERT INTO Product([ Name ],Color) VALUES ( '微波炉' , '白色' ) INSERT INTO Product([ Name ],Color) VALUES ( '笔记本' , '红色' ) INSERT INTO Product([ Name ],Color) VALUES ( '电脑' , '红色' ) INSERT INTO Product([ Name ],Color) VALUES ( '办公桌' , '红色' ) INSERT INTO Product([ Name ],Color) VALUES ( '轿车' , '红色' ) INSERT INTO Product([ Name ],Color) VALUES ( '笔' , '红色' ) INSERT INTO Product([ Name ],Color) VALUES ( '纸张' , '红色' ) CREATE TABLE ProjectProduct ( ProjectID INT FOREIGN KEY REFERENCES Projects(ProjectID), ProductID INT FOREIGN KEY REFERENCES Product(ProductID) ) GO INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (1,2) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (1,3) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (1,4) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (1,6) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (2,1) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (2,2) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (2,3) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (2,4) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (2,7) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES (2,8) CREATE TABLE Tasks ( TaskID INT IDENTITY(1,1) PRIMARY KEY , [ Name ] VARCHAR (50) NULL , ProjectID INT FOREIGN KEY REFERENCES Projects(ProjectID) ) GO INSERT INTO Tasks([ Name ],ProjectID) VALUES ( '提醒交货' ,1) INSERT INTO Tasks([ Name ],ProjectID) VALUES ( '提醒验收' ,2) |
1 2 3 4 5 6 7 8 9 10 11 12 13 | /// <summary> /// /// </summary> public class Customers { public virtual int customer_id { get ; protected set ; } public virtual string name { get ; set ; } public virtual string email { get ; set ; } public virtual string contact_person { get ; set ; } public virtual string postal_address { get ; set ; } public virtual string physical_address { get ; set ; } public virtual string contact_number { get ; set ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using FluentNHibernate.Mapping; namespace CodeBlogdeom { /// <summary> /// /// </summary> class CustomersMap : ClassMap<Customers> { /// <summary> /// /// </summary> public CustomersMap() { Id(x => x.customer_id); Map(x => x.name); Map(x => x.email); Map(x => x.contact_person); Map(x => x.postal_address); Map(x => x.physical_address); Map(x => x.contact_number); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Globalization; using NHibernate.Persister; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using NHibernate.Cfg; //http://www.kode-blog.com/2014/04/fluent-nhibernate-tutorial-c-windows-crud-example/ namespace CodeBlogdeom { /// <summary> /// /// </summary> public partial class frmCustomers : Form { #region declarations ISessionFactory sessionFactory; #endregion #region methods private void load_records( string sFilter = "" ) { try { sessionFactory = CreateSessionFactory(); using ( var session = sessionFactory.OpenSession()) { string h_stmt = "FROM Customers" ; if (sFilter != "" ) { h_stmt += " WHERE " + sFilter; } IQuery query = session.CreateQuery(h_stmt); IList<Customers> customersList = query.List<Customers>(); dgvListCustomers.DataSource = customersList; lblStatistics.Text = "Total records returned: " + customersList.Count; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private static ISessionFactory CreateSessionFactory() { ISessionFactory isessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005 .ConnectionString( @"Server=GEOVINDU-PC\GEOVIN; Database=NHibernateSimpleDemo; Integrated Security=SSPI;" )) .Mappings(m => m .FluentMappings.AddFromAssemblyOf<frmCustomers>()) .BuildSessionFactory(); return isessionFactory; } /// <summary> /// /// </summary> /// <param name="customer_id"></param> private void load_customer_details( int customer_id) {<br> sessionFactory = CreateSessionFactory(); using (ISession session = sessionFactory.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { try { IQuery query = session.CreateQuery( "FROM Customers WHERE customer_id = " + customer_id); Customers customer = query.List<Customers>()[0]; txtCustomerId.Text = customer.customer_id.ToString(); txtName.Text = customer.name; txtEmail.Text = customer.email; txtContactPerson.Text = customer.contact_person; txtContactNumber.Text = customer.contact_number; txtPostalAddress.Text = customer.postal_address; txtPhysicalAddress.Text = customer.physical_address; } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception Msg" ); } } } } #endregion /// <summary> /// /// </summary> public frmCustomers() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load( object sender, EventArgs e) { load_records(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClose_Click( object sender, EventArgs e) { Close(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnFilter_Click( object sender, EventArgs e) { string sFilterValue = string .Empty; string sField = cboFilter.Text; string sCriteria = cboCriteria.Text; string sValue = txtValue.Text; switch (sCriteria) { case "Equals" : sFilterValue = sField + " = '" + sValue + "'" ; break ; case "Begins with" : sFilterValue = sField + " LIKE '" + sValue + "%'" ; break ; case "Contains" : sFilterValue = sField + " LIKE '%" + sValue + "%'" ; break ; case "Ends with" : sFilterValue = sField + " LIKE '%" + sValue + "'" ; break ; } //data.Add(sFilterValue, sValue); load_records(sFilterValue); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvListCustomers_Click( object sender, EventArgs e) { int customer_id = 0; customer_id = int .Parse(dgvListCustomers.CurrentRow.Cells[0].Value.ToString()); load_customer_details(customer_id); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAddNew_Click( object sender, EventArgs e) { //data validation if (txtName.Text == "" ) { MessageBox.Show( "The name field is required" , "Null name" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (txtEmail.Text == "" ) { MessageBox.Show( "The email field is required" , "Null email" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (txtPhysicalAddress.Text == "" ) { MessageBox.Show( "The physical address field is required" , "Null physical address" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } Customers customer = new Customers(); customer.name = txtName.Text; customer.email = txtEmail.Text; customer.contact_person = txtContactPerson.Text; customer.contact_number = txtContactNumber.Text; customer.physical_address = txtPhysicalAddress.Text; customer.postal_address = txtPostalAddress.Text; sessionFactory = CreateSessionFactory(); using ( var session = sessionFactory.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { try { session.Save(customer); transaction.Commit(); load_records(); } catch (Exception ex) { transaction.Rollback(); MessageBox.Show(ex.Message, "Exception Msg" ); } } } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRefresh_Click( object sender, EventArgs e) { load_records(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUpdate_Click( object sender, EventArgs e) { //data validation if (txtName.Text == "" ) { MessageBox.Show( "The name field is required" , "Null name" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (txtEmail.Text == "" ) { MessageBox.Show( "The email field is required" , "Null email" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } if (txtPhysicalAddress.Text == "" ) { MessageBox.Show( "The physical address field is required" , "Null physical address" , MessageBoxButtons.OK, MessageBoxIcon.Warning); return ; } sessionFactory = CreateSessionFactory(); using ( var session = sessionFactory.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { try { IQuery query = session.CreateQuery( "FROM Customers WHERE customer_id = '" + txtCustomerId.Text + "'" ); Customers customer = query.List<Customers>()[0]; customer.name = txtName.Text; customer.email = txtEmail.Text; customer.contact_person = txtContactPerson.Text; customer.contact_number = txtContactNumber.Text; customer.physical_address = txtPhysicalAddress.Text; customer.postal_address = txtPostalAddress.Text; session.Update(customer); transaction.Commit(); load_records(); } catch (Exception ex) { transaction.Rollback(); MessageBox.Show(ex.Message, "Exception Msg" ); } } } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnDelete_Click( object sender, EventArgs e) {<br> sessionFactory = CreateSessionFactory(); using (ISession session = sessionFactory.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { try { IQuery query = session.CreateQuery( "FROM Customers WHERE customer_id = '" + txtCustomerId.Text + "'" ); Customers customer = query.List<Customers>()[0]; session.Delete(customer); //delete the record transaction.Commit(); //commit it btnRefresh_Click(sender, e); } catch (Exception ex) { transaction.Rollback(); MessageBox.Show(ex.Message, "Exception Msg" ); } } } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using NHibernate.Tool.hbm2ddl; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace JaxaraRnD.Helpers.DataAccess { public class FluentNHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null ) InitializeSessionFactory(); return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008.ConnectionString(JaxaraRnDUtility.Constants.DEFAULT_CONNECTION).ShowSql()) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<FluentNHibernateHelper>()) //.ExposeConfiguration(c => new SchemaExport(c).Create(true, true)) //会清除数据 .BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } } |
注意这些连接的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | /// <summary> /// /// </summary> /// <returns></returns> private static ISessionFactory CreateSessionFactory() { ISessionFactory isessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005 .ConnectionString( @"Server=LF-WEN\GEOVINDU;initial catalog=NHibernateSimpleDemo;User ID=sa;Password=520;" )) .Mappings(m => m //.FluentMappings.PersistenceModel //.FluentMappings.AddFromAssembly(); .FluentMappings.AddFromAssemblyOf<Form1>()) .BuildSessionFactory(); return isessionFactory; } /// <summary> /// /// </summary> /// <returns></returns> private static ISessionFactory CreateSessionFactoryTwo() { ISessionFactory isessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005 .ConnectionString( @"Server=LF-WEN\GEOVINDU;initial catalog=NHibernateSimpleDemo;User ID=sa;Password=520;" )) //.Mappings(m=>m // .FluentMappings.AddFromAssemblyOf<Form1>()) .Mappings(m => { var persistenceModel = new PersistenceModel() { ValidationEnabled = false }; m.UsePersistenceModel(persistenceModel) .FluentMappings.AddFromAssemblyOf<Employee>(); }) .BuildSessionFactory(); return isessionFactory; } /// <summary> /// /// </summary> /// <returns></returns> public static ISessionFactory GetCurrentFactory() { if (sessionFactoryOne == null ) { sessionFactoryOne = CreateSessionFactoryOne(); } return sessionFactoryOne; } /// <summary> /// 映射调用出问题 /// </summary> /// <returns></returns> private static ISessionFactory CreateSessionFactoryOne() { return FluentNHibernate.Cfg.Fluently.Configure() .Database( FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2005 .ConnectionString(s => s.Server( @"LF-WEN\GEOVINDU" ) .Database( "NHibernateSimpleDemo" ) .Username( "sa" ) .Password( "520" ) .TrustedConnection()) ).BuildSessionFactory(); } /// <summary> /// /// </summary> private static ISessionFactory sessionFactoryOne { get ; set ; } /// <summary> /// /// </summary> private static void InitializeSessionFactory() { try { _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(JaxaraRnDUtility.Constants.DEFAULT_CONNECTION).ShowSql()) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<FluentNHibernateHelper>()) .ExposeConfiguration(c => new SchemaExport(c).Create( true , true )) .BuildSessionFactory(); } catch (Exception ex) { Console.Write(ex.Message.ToString()); } } |
https://dotblogs.com.tw/hatelove/archive/2009/09/17/10686.aspx
http://www.cnblogs.com/inday/archive/2009/08/04/Study-Fluent-NHibernate-Start.html
http://www.codeproject.com/Articles/19425/NHibernate-Templates-for-Smart-Code-Generator
http://www.codeproject.com/Articles/247196/Components-Mapping-in-Fluent-NHibernate
http://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat
http://mvcfhibernate.codeplex.com/ VS2012打开
http://blog.csdn.net/zhang_xinxiu/article/details/42131907
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2012-03-27 Csharp Winform TextBox 樣式以一條橫線顯示