• 我的第一个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 > 0 ? items[0] : 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);
        }
    }
    View Code

     7.View代码

    ViewsHomeCreate.cshtml

     1 @model IEnumerable<FluentNHibernateDemo1.Models.Item>
     2 
     3 @{
     4     Layout = null;
     5 }
     6 
     7 <!DOCTYPE html>
     8 
     9 <html>
    10 <head>
    11     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    12     <meta name="viewport" content="width=device-width" />
    13     <title>Index</title>
    14 </head>
    15 <body>
    16     <p>
    17         @Html.ActionLink("Create New", "Create")
    18     </p>
    19     <table class="table">
    20         <tr>
    21             <th>
    22                 @Html.DisplayNameFor(model => model.Name)
    23             </th>
    24             <th>
    25                 @Html.DisplayNameFor(model => model.Age)
    26             </th>
    27             <th>
    28                 @Html.DisplayNameFor(model => model.Description)
    29             </th>
    30             <th></th>
    31         </tr>
    32     
    33     @foreach (var item in Model) {
    34         <tr>
    35             <td>
    36                 @Html.DisplayFor(modelItem => item.Name)
    37             </td>
    38             <td>
    39                 @Html.DisplayFor(modelItem => item.Age)
    40             </td>
    41             <td>
    42                 @Html.DisplayFor(modelItem => item.Description)
    43             </td>
    44             <td>
    45                 @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
    46                 @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    47             </td>
    48         </tr>
    49     }
    50     
    51     </table>
    52 </body>
    53 </html>
    Index.cshtml
     1 <!DOCTYPE html>
     2 
     3 <html>
     4 <head>
     5     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
     6     <meta name="viewport" content="width=device-width" />
     7     <title>Create</title>
     8     <script src="~/Scripts/jquery-1.9.1.min.js"></script>
     9     <script src="~/Scripts/jquery.validate.min.js"></script>
    10     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    11 </head>
    12 <body>
    13     
    14     
    15     @using (Html.BeginForm()) 
    16     {
    17         @Html.AntiForgeryToken()
    18         
    19         <div class="form-horizontal">
    20             <h4>Item</h4>
    21             <hr />
    22             @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    23             <div class="form-group">
    24                 @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
    25                 <div class="col-md-10">
    26                     @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
    27                     @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
    28                 </div>
    29             </div>
    30     
    31             <div class="form-group">
    32                 @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
    33                 <div class="col-md-10">
    34                     @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
    35                     @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
    36                 </div>
    37             </div>
    38     
    39             <div class="form-group">
    40                 @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
    41                 <div class="col-md-10">
    42                     @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
    43                     @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
    44                 </div>
    45             </div>
    46     
    47             <div class="form-group">
    48                 <div class="col-md-offset-2 col-md-10">
    49                     <input type="submit" value="Create" class="btn btn-default" />
    50                 </div>
    51             </div>
    52         </div>
    53     }
    54     
    55     <div>
    56         @Html.ActionLink("Back to List", "Index")
    57     </div>
    58 </body>
    59 </html>
    Create.cshtml
     1 @model FluentNHibernateDemo1.Models.Item
     2 
     3 @{
     4     Layout = null;
     5 }
     6 
     7 <!DOCTYPE html>
     8 
     9 <html>
    10 <head>
    11     <meta name="viewport" content="width=device-width" />
    12     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    13     <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    14     <script src="~/Scripts/jquery.validate.min.js"></script>
    15     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    16 
    17     <title>Edit</title>
    18 </head>
    19 <body>
    20 
    21 
    22     @using (Html.BeginForm())
    23     {
    24         @Html.AntiForgeryToken()
    25 
    26         <div class="form-horizontal">
    27             <h4>Item</h4>
    28             <hr />
    29             @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    30             @Html.HiddenFor(model => model.Id)
    31 
    32             <div class="form-group">
    33                 @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
    34                 <div class="col-md-10">
    35                     @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
    36                     @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
    37                 </div>
    38             </div>
    39 
    40             <div class="form-group">
    41                 @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
    42                 <div class="col-md-10">
    43                     @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
    44                     @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
    45                 </div>
    46             </div>
    47 
    48             <div class="form-group">
    49                 @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
    50                 <div class="col-md-10">
    51                     @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
    52                     @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
    53                 </div>
    54             </div>
    55 
    56             <div class="form-group">
    57                 <div class="col-md-offset-2 col-md-10">
    58                     <input type="submit" value="Save" class="btn btn-default" />
    59                 </div>
    60             </div>
    61         </div>
    62     }
    63 
    64     <div>
    65         @Html.ActionLink("Back to List", "Index")
    66     </div>
    67 </body>
    68 </html>
    Edit.cshtml
     1 @model FluentNHibernateDemo1.Models.Item
     2 
     3 @{
     4     Layout = null;
     5 }
     6 
     7 <!DOCTYPE html>
     8 
     9 <html>
    10 <head>
    11     <meta name="viewport" content="width=device-width" />
    12     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    13     <title>Delete</title>
    14 </head>
    15 <body>
    16     <div>
    17         <h4>Item</h4>
    18         <hr />
    19         <dl class="dl-horizontal">
    20             <dt>
    21                 @Html.DisplayNameFor(model => model.Name)
    22             </dt>
    23     
    24             <dd>
    25                 @Html.DisplayFor(model => model.Name)
    26             </dd>
    27     
    28             <dt>
    29                 @Html.DisplayNameFor(model => model.Age)
    30             </dt>
    31     
    32             <dd>
    33                 @Html.DisplayFor(model => model.Age)
    34             </dd>
    35     
    36             <dt>
    37                 @Html.DisplayNameFor(model => model.Description)
    38             </dt>
    39     
    40             <dd>
    41                 @Html.DisplayFor(model => model.Description)
    42             </dd>
    43     
    44         </dl>
    45     </div>
    46     <p>
    47         @Html.ActionLink("Delete", "DeleteConfirm", new { id = Model.Id }) |
    48         @Html.ActionLink("Back to List", "Index")
    49     </p>
    50 </body>
    51 </html>
    Delete.cshtml

    8.好了,在chrome中运行正常

    Index

    Create

    Edit

    附上完整代码:

    http://pan.baidu.com/s/1sloW1M9

    密码: 9zhr

    本人第一个例子,有不足之处欢迎指正

      

  • 相关阅读:
    电脑连接到手机并安装手机驱动usb-driver
    创建安卓模拟器的两种方式及常用Android命令介绍
    在loadrunner中用头文件的形式对字符串进行MD5加密操作
    Android自动化测试Uiautomator--UiCollection接口简介
    Android自动化测试Uiautomator--UiScrollable接口简介
    Android自动化测试Uiautomator--UiObject接口简介
    Android自动化测试Uiautomator--UiSelector接口简介
    Uiautomator简介及其环境搭建、测试执行
    Android自动化测试Uiautomator--UiDevice接口简介
    Eclipce 配置javaEE
  • 原文地址:https://www.cnblogs.com/conan77/p/5373480.html
Copyright © 2020-2023  润新知