刚刚接触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例子的更多相关文章

  1. 我的第二个FluentNHibernate例子with Knockout

    在上一篇我的第一个FluentNHibernate例子的基础上,我们用上knockoutjs 1用nuget添加knockoutjs包 2用nuget添加json.net包 3..在Index.csh ...

  2. SQL Server Reporting Service(SSRS) 第一篇 我的第一个SSRS例子

    很早就知道SQL SERVER自带的报表工具SSRS,但一直没有用过,最近终于需要在工作中一展身手了,于是我特地按照自己的理解做了以下总结: 1. 安装软件结构 SSRS全称SQL Server Re ...

  3. 一个简单例子:贫血模型or领域模型

    转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...

  4. java连接mysql的一个小例子

    想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径 在eclipse中,Project的properties里面的java build path里面添加引用 连接成功的一 ...

  5. java操作xml的一个小例子

    最近两天公司事比较多,这两天自己主要跟xml打交道,今天更一下用java操作xml的一个小例子. 原来自己操作xml一直用这个包:xstream-1.4.2.jar.然后用注解的方式,很方便,自己只要 ...

  6. MVVM模式的一个小例子

    使用SilverLight.WPF也有很长时间了,但是知道Binding.Command的基本用法,对于原理性的东西,一直没有深究.如果让我自己建一个MVVM模式的项目,感觉还是无从下手,最近写了一个 ...

  7. Lea指令计算地址(用于四则混合运算),附上一个函数调用例子及其反汇编代码,很清楚

    比如你用local在栈上定义了一个局部变量LocalVar,你知道实际的指令是什么么?一般都差不多像下面的样子:     push   ebp     mov   esp,   ebp     sub ...

  8. (转)Java中使用正则表达式的一个简单例子及常用正则分享

    转自:http://www.jb51.net/article/67724.htm 这篇文章主要介绍了Java中使用正则表达式的一个简单例子及常用正则分享,本文用一个验证Email的例子讲解JAVA中如 ...

  9. C语言多线程的一个简单例子

    多线程的一个简单例子: #include <stdio.h> #include <stdlib.h> #include <string.h> #include &l ...

随机推荐

  1. 邮箱、手机号、中文 js跟php正则验证

    邮箱正则: jS: var regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; //验证 if(regEmail.te ...

  2. 为川师大女生支招 15年如何还200W

    就在昨儿一条新闻火遍全网,川师大21岁女生樊师贝发帖称,希望有人借她200万,为父母在城里买房15年还清,至于利息“可以用后半生来陪伴你”.她说,六旬父亲要负担家用,哥哥啃老,而她目前一分钱都还没挣到 ...

  3. android studio 问题1

    在使用androidStudio中,经常导入其他的项目,有时候会出现以下错误: rror:FAILURE: Build failed with an exception. * What went wr ...

  4. sql server 权限体系

    --给sql server添加一个新用户[账号,密码,数据库名] execute  sp_addlogin 'baishi', '123','db'; execute  sp_addlogin 'wx ...

  5. js回调函数,字符串,数组小析

    (一)回调函数:是指通过函数参数传递到其他代码的,某一块可执行代码的引用.这一设计允许了底层代码调用在高层定义的子程序.在抖动函数中,回调函数用于在实现一些功能之后采取的另外的措施,比如div,照片抖 ...

  6. jQuery( )方法的构建原理

    jQuery中最常用方法的就是jQuery( ),也即$( ). jQuery( )是一个函数调用,调用的结果是返回了一个jQuery实例对象. 编写组件通常的做法是将组件封装成一个对象,需要用的时候 ...

  7. ansible 小试

    安装: pip install ansible 添加配置文件: 配置文件查找顺序 * ANSIBLE_CONFIG (环境变量) * ansible.cfg (当前目录下) * .ansible.cf ...

  8. centos6.7下安装mvn 、安装elasticsearch下ik分词

    先说一下安装mvn步骤,如果已安装可以忽略: 在tmp目录下 1.建立mvn目录 mkdir mvn cd /tmp/mvn 2.下载 wget http://apache.fayea.com/mav ...

  9. yii2.0场景的使用

  10. redis学习教程地址

    http://www.yiibai.com/redis/redis_quick_guide.html