我的第一个FluentNHibernate例子
刚刚接触NHibernate和FluentNHibernate,所以最好的方法是从一个简单的例子入手。
开发环境考虑到是实际情况还有好多朋友没有用VS2015,就用VS2013withUpdate5吧。
1.创建Asp.net Web应用程序(MVC),叫FluentNHibernateDemo1

选择Empty,MVC

2.管理NuGet程序包
添加FluentNHibernate,2.0.3.0
添加bootstrap

添加jquery.validate.unobtrusive

添加JQuery validation with bootstrap

3.添加Model
public class Item
{
[Key]
public virtual int Id { get; set; }
[Display(Name = "姓名")]
[Required(ErrorMessage = "姓名必须")]
public virtual string Name { get; set; }
[Display(Name = "年龄")]
[Required(ErrorMessage = "年龄必须")]
public virtual int Age { get; set; }
[Display(Name = "描述")]
public virtual string Description { get; set; }
}
4.添加Map,注意这里使用C#完成映射
public class ItemMap:ClassMap<Item>
{
public ItemMap()
{
Table("Item");
Id(m => m.Id).GeneratedBy.Native();
Map(m => m.Name).Length(50).Not.Nullable();
Map(m => m.Age).Not.Nullable();
Map(m => m.Description).Length(500);
}
}
5.添加NHibernate help类
public class NHibernateHelper
{
private const string exportFilePath = @"c:\abc.sql";
public static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration
.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<ItemMap>()).ExposeConfiguration(CreateSchema)
.BuildSessionFactory();
}
private static void CreateSchema(Configuration cfg)
{
var schemaExport = new SchemaExport(cfg);
var str = cfg.Properties["connection.connection_string"].ToString();
bool isNew = isNewDb(str);
if (isNew)
{
if (System.IO.File.Exists(exportFilePath))
System.IO.File.Delete(exportFilePath);
schemaExport.SetOutputFile(exportFilePath);
}
schemaExport.Create(false, isNew);
} private static bool isNewDb(string connectString)
{
bool isNew = false;
try
{
using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
string sql = "select * FROM Item";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteReader(CommandBehavior.CloseConnection);
} }
catch
{
isNew = true;
}
return isNew;
}
}
这里要解释一下:
a)
ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
是指在web.config中配置在web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Demo.mdf;Initial Catalog=test;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
我采用的是Vs2013自带的localdb,数据库名为Demo.mdf,所以我先要建一个空的数据库(Demo.mdf),至于表,我会用CodeFirst生成。

b)
bool isNew = isNewDb(str);
schemaExport.Create(false, isNew);
原因是当数据库为空是我们要用schemaExport.Create(false, true);
这时会生成数据库
当数据库存在表时,我们要用schemaExport.Create(false, false);
如果是schemaExport.Create(false, true);会出现无法新增数据的情况
6.新建Home Controller


Controller 代码:
public class HomeController : Controller
{
public ActionResult Create()
{
return View();
}
public ActionResult Edit(int id)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{
IList<Item> items = session.CreateCriteria(typeof(Item))
.Add(Restrictions.Eq("Id", id))
.List<Item>();
var result = items.Count > ? items[] : null;
return View(result);
}
}
[HttpPost]
public ActionResult Edit(Item item)
{
if (ModelState.IsValid)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{ session.Update(item, item.Id);
session.Flush();
}
}
return RedirectToAction("Index");
}
public ActionResult DeleteConfirm(int id)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{
// IList<Item> items = session.CreateCriteria(typeof(Item))
// .Add(Restrictions.Eq("Id", id))
// .List<Item>();
// var result = items.Count > 0 ? items[0] : null;
// if (result != null)
// session.Delete(result);
session.Delete("From Item where Id=" + id);
session.Flush();
return RedirectToAction("Index");
}
}
public ActionResult Delete(int id)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{
var result = session.Get<Item>(id);
return View(result);
}
} [HttpPost]
public ActionResult Create(Item item)
{
if (ModelState.IsValid)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{ session.Save(item);
session.Flush();
}
}
return RedirectToAction("Index");
}
// GET: Home
public ActionResult Index()
{
var factory = NHibernateHelper.CreateSessionFactory();
IEnumerable<Item> items;
using (var session = factory.OpenSession())
{
items = session.CreateQuery("from Item").List<Item>();
}
return View(items);
}
}
7.View代码
Views\Home\Create.cshtml

@model IEnumerable<FluentNHibernateDemo1.Models.Item>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
</body>
</html>
Index.cshtml
<!DOCTYPE html> <html>
<head>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
<title>Create</title>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</head>
<body> @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Item</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
} <div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
Create.cshtml
@model FluentNHibernateDemo1.Models.Item
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<title>Edit</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Item</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
Edit.cshtml
@model FluentNHibernateDemo1.Models.Item
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<title>Delete</title>
</head>
<body>
<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Age)
</dt>
<dd>
@Html.DisplayFor(model => model.Age)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Description)
</dt>
<dd>
@Html.DisplayFor(model => model.Description)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Delete", "DeleteConfirm", new { id = Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>
Delete.cshtml
8.好了,在chrome中运行正常
Index

Create

Edit
附上完整代码:
http://pan.baidu.com/s/1sloW1M9
密码: 9zhr
本人第一个例子,有不足之处欢迎指正
我的第一个FluentNHibernate例子的更多相关文章
- 我的第二个FluentNHibernate例子with Knockout
在上一篇我的第一个FluentNHibernate例子的基础上,我们用上knockoutjs 1用nuget添加knockoutjs包 2用nuget添加json.net包 3..在Index.csh ...
- SQL Server Reporting Service(SSRS) 第一篇 我的第一个SSRS例子
很早就知道SQL SERVER自带的报表工具SSRS,但一直没有用过,最近终于需要在工作中一展身手了,于是我特地按照自己的理解做了以下总结: 1. 安装软件结构 SSRS全称SQL Server Re ...
- 一个简单例子:贫血模型or领域模型
转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...
- java连接mysql的一个小例子
想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径 在eclipse中,Project的properties里面的java build path里面添加引用 连接成功的一 ...
- java操作xml的一个小例子
最近两天公司事比较多,这两天自己主要跟xml打交道,今天更一下用java操作xml的一个小例子. 原来自己操作xml一直用这个包:xstream-1.4.2.jar.然后用注解的方式,很方便,自己只要 ...
- MVVM模式的一个小例子
使用SilverLight.WPF也有很长时间了,但是知道Binding.Command的基本用法,对于原理性的东西,一直没有深究.如果让我自己建一个MVVM模式的项目,感觉还是无从下手,最近写了一个 ...
- Lea指令计算地址(用于四则混合运算),附上一个函数调用例子及其反汇编代码,很清楚
比如你用local在栈上定义了一个局部变量LocalVar,你知道实际的指令是什么么?一般都差不多像下面的样子: push ebp mov esp, ebp sub ...
- (转)Java中使用正则表达式的一个简单例子及常用正则分享
转自:http://www.jb51.net/article/67724.htm 这篇文章主要介绍了Java中使用正则表达式的一个简单例子及常用正则分享,本文用一个验证Email的例子讲解JAVA中如 ...
- C语言多线程的一个简单例子
多线程的一个简单例子: #include <stdio.h> #include <stdlib.h> #include <string.h> #include &l ...
随机推荐
- 拓扑排序 - 并查集 - Rank of Tetris
Description 自从Lele开发了Rating系统,他的Tetris事业更是如虎添翼,不久他遍把这个游戏推向了全球. 为了更好的符合那些爱好者的喜好,Lele又想了一个新点子:他将制作一个全球 ...
- SecureCRT中python脚本编写
SecureCRT中python脚本编写学习指南 SecureCRT python 引言 在测试网络设备中,通常使用脚本对设备端进行配置和测试以及维护:对于PE设备的测试维护人员来说使用较多是Secu ...
- Python标准异常topic
Python标准异常topic AssertionError 断言语句 (assert) ...
- TEST===>Sqlserver中获取年月日时分秒
可以用两种方法获取 1. select GETDATE() as '当前日期', DateName(year,GetDate()) as '年', DateName(month,GetDate()) ...
- 不可变字符串NSString
/*字符串的常用方法*/ //1.通常用来把一些基本数据类型和字符串进行拼接 ; float b = 9527.0; NSString *string = [NSString stringWithFo ...
- 分部方法 partial
当有如下这样类似的情况出现的时候,可以有更好的优化方式来处理,那就是分部方法 class PartOld { string name; public virtual void OnChangeName ...
- jquery插件学习之元素顶部悬浮
jquery插件的学习: HTML部分及应用 <!DOCTYPE html> <html> <head> <meta charset="utf-8& ...
- 关于如何在MVC中 执行JS
Response.Write("<script>KHTPREFERENCE()</script>"); return this.MessageResult( ...
- Lua模块
在lua中,我们可以直接使用require(“model_name”)来载入别的文件,文件的后缀名是.lua,载入的时候直接执行那个文件了. 比如:my.lua 文件中 print(“hello wo ...
- java读取项目中文件路径及乱码解决
this.getClass.getResource(path).getPath(); 如果出现中文乱码,可以使用java.net.URLDecoder.decode方法进行处理 如:URLDecode ...