我的第一个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 ...
随机推荐
- 从零开始山寨Caffe·零:必先利其器
工作环境 巧妇有了米炊 众所周知,Caffe是在Linux下写的,所以长久以来,大家都认为跑Caffe,先装Linux. niuzhiheng大神发起了caffe-windows项目(解决了一些编译. ...
- Leetcode Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...
- 单元测试地二蛋 先弄个两个原生模块1个原始的一个jq插件
放羊测试测完了再测这两个瞎搞的下拉列表组建 看看从单元测试模块化的角度组建会写成啥样 1:ajax请求 简单文本 2:1个页面多个实例 3:复杂展示+自定义点击+自定义处理函数 ...
- 2016最新 wamp2.5+windows 10安装CoedSgniffer代码格式检查:5分钟安装 30分钟入门和浏览常用命令
14:59 2016/1/112016最新 wamp2.5+windows 10安装CoedSgniffer代码格式检查:注意问题:1.手动安装2.5.0和pear安装方式都成功但是执行时无任何反映, ...
- LINUX内核参数网络相关
有助于提高网络性能和吞吐量的参数 net.core.somaxconn = 128 已完成连接队列(completed connection queue) (1)三次握手已经完成,但还未被应用层接收( ...
- ZeroMQ接口函数之 :zmq_errno – 返回errno的值给调用此函数的线程
ZeroMQ 官方地址 :http://api.zeromq.org/4-0:zmq_errno zmq_errno(3) ØMQ Manual - ØMQ/3.2.5 Name zm ...
- Django 视图与网址进阶
一 .在网页上做加减法 1. 采用 /add/?a=4&b=5 这样GET方法进行 1 2 3 django-admin.py startproject zqxt_views cd zqxt_ ...
- 将博客从jekyll迁移到了hexo
关于hexo和jekyll hexo和jekyll一样都是个静态网站生成工具,hexo是一个台湾小伙使用nodejs开发的,jekyll则是用ruby开发,github内置了jekyll,可以直接将j ...
- webrtc初识
最近由于项目的需求,开始接触了webrtc这个东西.没想到这东西的门槛还是蛮高的,接下来分享一下我所踩过的坑,希望对以后初次接触这个东西的人有所帮助. webrtc官网 第一步当然是看官方主页了(ww ...
- 安装运行Hadoop
1 准备环境 1.1 Ubuntu 或者 VMware Workstation Pro+Ubuntu 1.2 Jdk 1.3 eclipse 或其他开发工具(可选) 2 安装Hadoop 2.1 从h ...