65.9K
CodeProject 正在变化。 阅读更多。
Home

NHibernate with MVC3 Razor Engine

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (3投票s)

2013年8月13日

CPOL

5分钟阅读

viewsIcon

30437

downloadIcon

1375

这里我们将使用 MVC3 Razor 引擎创建 NHibernate 架构。

介绍 

我们将为使用 Razor 引擎的 MVC3 创建 NHibernate 架构。在开始本教程之前,您应该熟悉 MVC3、Razor 和 NHibernate。NHibernate 使用对象关系映射 (ORM)。您可以在同一网站的另一个教程中找到基本信息。在这里,我们将使用 NHibernate 架构和 MVC3 Razor 引擎创建一个基本而简单的应用程序。

背景

您将在此处获得基本信息

使用代码

我们一步一步来。

首先,启动您的 Visual Studio => 选择新的 MVC3 应用程序项目。确保您选择了 Razor 引擎。您将拥有带有 Razor 的 MVC3 示例站点。使用NuGet 包安装 Nhibernate 包。这样您将获得NHibernate.dll及其依赖项Iesi.Collection.dll的 DLL。此步骤对您来说是可选的,因为您也可以从附件来源找到 DLL,但如果它对您不起作用,那么您应该通过安装包自己创建它。然后运行附加的数据库脚本。您将拥有一个名为NHibernate101的数据库。

现在分别命名为CoreInfrasturcture的两个类库。将NHibernate.dll及其依赖项Iesi.Collection.dll的引用添加到 Core 库(如果您使用 NuGet 包安装了它,您会在包文件夹中找到它),然后创建接口IRespository.cs(可以从附加的源代码获取)

代码块

namespace Core
{
    public interface IRepository<T>
    {
        void Save(T entity);
        void Update(T entity);
        void Delete(T entiy);
        T GetById(Guid id);
        IList<T> GetAll();
    }
}

现在在 Core 库中创建 Domain 文件夹,并在 Domain 文件夹下创建 Model 和 Repositories。在 Model 文件夹中,我们将创建实体类,在 Repositories 文件夹中,我们将创建 CRUD 方法。您需要额外做一件事,就是在 Repositories 文件夹中添加NHibernateHelper.cs。您将从源代码中获取它。

在 Model 文件夹中创建实体类Category.cs

namespace Core.Domain.Model
{
    public class Category
    {
        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }
    }
}

Repositories文件夹中创建CategoryRepository.cs。它实现了我们之前创建的IRepository接口。在这里,我们用 Category 实体实现了IRepository。我们还重写了接口中定义的所有方法。这个类包含对 Category 进行 CRUD(创建、检索、更新和删除)的方法。

namespace Core.Domain.Repositories
{
    public class CategoryRepository:IRepository<Category>
    {
        #region IRepository<Category> Members

        void IRepository<Category>.Save(Category entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<Category>.Update(Category entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<Category>.Delete(Category entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(entity);
                    transaction.Commit();
                }
            }
        }

        Category IRepository<Category>.GetById(Guid id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<Category>().Add(
                  Restrictions.Eq("Id", id)).UniqueResult<Category>();
        }

        IList<Category> IRepository<Category>.GetAll()
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Category));
                return criteria.List<Category>();
            }
        }

        #endregion
    }
}

现在 Core Library 已准备好使用。所以我们继续我们的另一个库 Infrastructure。在这里,我们正在映射对象。

第一步,创建一个用于数据库配置的 xml 文件。确保其扩展名以 .cfg.xml 结尾(这里是hibernate.cfg.xml)。将此代码添加到其中。

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">
    PASTE YOUR CONNECTIONSTRING HERE
    </property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="cache.use_query_cache">false</property>
    <property name="adonet.batch_size">100</property>
    <mapping assembly="Infrasturcture" />
  </session-factory>
</hibernate-configuration>

现在转到此文件的属性,并将**复制到输出目录**设置为**始终复制**。

现在我们创建用于对象映射的 xml 文件。为此,请创建一个名为**DataAccess**的文件夹。然后在其中创建一个**Mappings**文件夹。现在我们正在处理 Category 表,所以我们将为它创建一个对象映射文件。所以,在 Mappings 文件夹中创建一个Category.hbm.xml文件。这是一个简单的 XML 文件,但确保它的扩展名为.hbm.xmlCategory.hbm.xml的代码块是

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   namespace="Core.Domain.Model"
                   assembly="Core">

  <class name="Category" table="Categories" dynamic-update="true">
    <cache usage="read-write"/>
    <id name="Id" column="Id" type="Guid">
      <generator class="guid"/>
    </id>
    <property name="Name" length="100"/>
  </class>
</hibernate-mapping>

这里的命名空间是 Core.Domain.Model,我们在其中创建了实体类。在映射文件中,我们必须提及数据库 Category 表中存在的列名(及其相应的数据类型和长度)。现在选择Category.hbm.xml的属性,然后将**生成操作**设置为**嵌入式资源**。现在我们的基础设施库也已准备好使用。

生成两个库,然后继续我们的 MVC 应用程序。提供两个项目(Core 和 Infrasturcture)的引用。现在我们创建 MVC Application.Remove已存在的视图、控制器和模型。我们将创建自己的(不要删除 Views 中的共享文件夹)。

现在创建一个名为CategoriesController.cs的控制器,这里我们显示 category 表中的所有 category。所以,为 Index 方法(它是默认的)编写代码。

public ActionResult Index()
{
    IRepository<Category> repo = new CategoryRepository();
    return View(repo.GetAll());
}

现在单击方法名称并为其添加相应的视图(您应该熟悉 MVC 模式)。

Index.cshtml中显示 category 的代码是

@{ //index.cshtml
    ViewBag.Desc = "MVC3 Razor";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Categories</h2>

    <table>
        <tr>
            <th></th>
            <th>
                Name
            </th>
            <th></th>
        </tr>

    @foreach (var item in Model) { 
    
        <tr>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id })
            </td>
            <td>
                @Html.Encode(item.Name)
            </td>
            <td>
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    
    } 

    </table>

    <p>
        @Html.ActionLink("Create New", "Create")
    </p>

现在转到global.aspx.cs,并在 Register Route 方法中将默认控制器名称替换为“Categories”。现在运行您的 MVC 应用程序,您将看到所有 category 的列表。如果数据库中没有任何记录,请不要担心,我们创建了一个用于插入 category 的页面。

为渲染Create.cshtml添加Create方法

public ActionResult Create()
{ //this method render Create.cshml
    return View();
}
@{ //Create.cshtml
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>
        Create Category</h2>
    @Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")
    @using (Html.BeginForm()){
    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Name">
                Name:</label>
            @Html.TextBox("Name")
            @Html.ValidationMessage("Name", "*")
        </p>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
     } 
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

现在,当您单击 Category 列表页面上的创建新按钮时,您将进入一个用于插入 category 的页面。在您按下 Create 按钮之前,我们必须创建一个用于保存数据的方法。所以,添加Create方法(这里是方法重载),它处理该页面的 post 方法并使用表单集合获取数据。

代码看起来像

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection formCollection)
{
    string name = formCollection.Get("Name");
    Category category = new Category() { Name = name };

    IRepository<Category> repo = new CategoryRepository();
    repo.Save(category);

    return RedirectToAction("Index");
}

现在在文本框中输入 category 名称并按提交按钮。您可以在 category 列表页面中看到最近添加的 category。现在我们处理编辑和删除。

要编辑 category,请在CategoriesController.cs中添加Edit方法,该方法渲染Edit.cshtml

public ActionResult Edit(Guid id)
{
    //When you click edit link from list you comes here for get particular record
    IRepository<Category> repo = new CategoryRepository();
    return View(repo.GetById(id));
}
@{   // Edit.cshtml
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit Category</h2>

@Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") 

@using (Html.BeginForm()) {

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Name">Name:</label>
            @Html.TextBox("Name", null, new { @value = Model.Name })
            @Html.ValidationMessage("Name", "*")
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

}

<div>
    @Html.ActionLink("Back to List", "Index") 
</div>

现在我们创建用于更新记录的方法。再次添加此方法以更新记录,它处理来自Edit.cshtml的 Post 操作。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, FormCollection formCollection)
{
    string name = formCollection.Get("Name");
    Category category = new Category() { Id = id, Name = name };

    IRepository<Category> repo = new CategoryRepository();
    repo.Update(category);

    return RedirectToAction("Index");
}

单击保存后,您将返回列表页面,可以看到修改后的记录。

现在我们创建添加用于删除的方法。创建此方法用于删除 category。

public ActionResult Delete(Guid id)
{
    IRepository<Category> repo = new CategoryRepository();
    repo.Delete(repo.GetById(id));
    return RedirectToAction("Index");
}

我们的 CRUD 操作到此结束。如果您仍有任何疑问,可以检查附件中的源代码。

值得关注的点  

当我开始使用带有 Razor 引擎的 MVC3 学习 NHibernate 时,我在 Google 上搜索了示例代码,但没有找到。然后我找到了一个使用 aspx 的示例应用程序,然后我以它为参考,使用 Razor 引擎创建了它。

历史

我将很快改进这篇文章。

© . All rights reserved.