ASP.NET Boilerplate can work with any O/RM framework. It has built-in integration with NHibernate. This document will explain how to use NHibernate with ASP.NET Boilerplate. It's assumed that you're already familar with NHibernate in a basic level.

ASP.NET样板可以与任何O / RM工作框架。它具有内置的集成NHibernate。本文档将解释如何使用NHibernate与ASP.NET样板。假定你已经熟悉了基本NHibernate。

Nuget package

Nuget package to use NHibernate as O/RM in ASP.NET Boilerplate is Abp.NHibernate. You should add it to your application. It's better to implement NHibernate in a seperated assembly (dll) in your application and depend on that package from this assembly.

NuGet包使用NHibernate在ASP.NET样板的O / RM是Abp.NHibernate。你应该把它添加到你的应用程序。最好是在一个分离的组件实现NHibernate(DLL)在你的应用和依赖,从这个组件包。

Configuration

To start using NHibernate, you should configure it in PreInitialize of your module.

[DependsOn(typeof(AbpNHibernateModule))]
public class SimpleTaskSystemDataModule : AbpModule
{
public override void PreInitialize()
{
var connStr = ConfigurationManager.ConnectionStrings["Default"].ConnectionString; Configuration.Modules.AbpNHibernate().FluentConfiguration
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(connStr))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()));
} public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}

AbpNHibernateModule module provides base functionality and adapters to make NHibernate work with ASP.NET Boilerplate.

Entity mapping

In this sample configuration above, we have fluently mapped using all mapping classes in current assembly. An example mapping class can be as shown below:

在上面的示例配置中,我们使用当前程序集中的所有映射类进行了流畅的映射。一个示例映射类可以如下所示:

public class TaskMap : EntityMap<Task>
{
public TaskMap()
: base("TeTasks")
{
References(x => x.AssignedUser).Column("AssignedUserId").LazyLoad(); Map(x => x.Title).Not.Nullable();
Map(x => x.Description).Nullable();
Map(x => x.Priority).CustomType<TaskPriority>().Not.Nullable();
Map(x => x.Privacy).CustomType<TaskPrivacy>().Not.Nullable();
Map(x => x.State).CustomType<TaskState>().Not.Nullable();
}
}

EntityMap is a class of ASP.NET Boilerplate that extends ClassMap<T>, automatically maps Id property and gets table name in the constructor. So, I'm deriving from it and mapping other properties using FluentNHibernate.  Surely, you can derive directly from ClassMap, you can use full API of FluentNHibernate and you can use other mapping techniques of NHibernate (like mapping XML files).

entitymap是一类ASP.NET样板延伸ClassMap <T>,自动地图ID属性在构造函数和获取表名。所以,我从它的其他性能和使用fluentnhibernate映射。当然,你可以直接来自ClassMap,您可以使用完整的API,你可以使用fluentnhibernate NHibernate其他映射技术(如XML文件)。

Repositories

Repositories are used to abstract data access from higher layers. See repository documentation for more.  存储库用于从高层抽象数据访问。

Default Implementation

Abp.NHibernate package implements default repositories for entities in your application. You don't have to create repository classes for entities to just use predefined repository methods.

abp.nhibernate包实现应用程序中的实体的默认库。您不必为实体创建存储库类,只使用预定义的存储库方法。

Example:

public class PersonAppService : IPersonAppService
{
private readonly IRepository<Person> _personRepository; public PersonAppService(IRepository<Person> personRepository)
{
_personRepository = personRepository;
} public void CreatePerson(CreatePersonInput input)
{
person = new Person { Name = input.Name, EmailAddress = input.EmailAddress }; _personRepository.Insert(person);
}
}

PersonAppService contructor-injects IRepository<Person> and uses the Insert method. In this way, you can easily inject IRepository<TEntity> (or IRepository<TEntity, TPrimaryKey>) and use predefined methods. Seerepository documentation for list of all predefined methods.

Custom Repositories

If you want to add some custom method, you should first add it to a repository interface (as a best practice), then implement in a repository class. ASP.NET Boilerplate provides a base class NhRepositoryBase to implement repositories easily. To implement IRepository interface, you can just derive your repository from this class.

如果您想添加一些自定义方法,您应该首先将其添加到存储库接口(作为最佳实践),然后在存储库类中实现。ASP.NET的模板提供了一个基类库nhrepositorybase实现容易。实施IRepository接口,你可以从这个类派生你的库。

Assume that we have a Task entity that can be assigned to a Person (entity) and a Task has a State (new, assigned, completed... and so on). We may need to write a custom method to get list of Tasks with some conditions and with AssisgnedPerson property pre-fetched in a single database query. See the example code:

假设我们有一个任务实体可以分配给一个人(实体),任务有一个状态(新的,分配的,完成的)…等等)。我们需要写一个获得有条件的任务列表的自定义方法和assisgnedperson预取在一个单一的数据库查询了。请参见示例代码:

public interface ITaskRepository : IRepository<Task, long>
{
List<Task> GetAllWithPeople(int? assignedPersonId, TaskState? state);
} public class TaskRepository : NhRepositoryBase<Task, long>, ITaskRepository
{
public TaskRepository(ISessionProvider sessionProvider)
: base(sessionProvider)
{
} public List<Task> GetAllWithPeople(int? assignedPersonId, TaskState? state)
{
var query = GetAll(); if (assignedPersonId.HasValue)
{
query = query.Where(task => task.AssignedPerson.Id == assignedPersonId.Value);
} if (state.HasValue)
{
query = query.Where(task => task.State == state);
} return query
.OrderByDescending(task => task.CreationTime)
.Fetch(task => task.AssignedPerson)
.ToList();
}
}

GetAll() returns IQueryable<Task>, then we can add some Where filters using given parameters. Finally we can call ToList() to get list of Tasks.

You can also use Session object in repository methods to use full API of NHibernate.

Note: Define the custom repository interface in the domain/core layer, implement it in the NHibernate project for layered applications. Thus, you can inject the interface from any project without referencing to NH.

注:定义域/核心层的自定义库的接口,实现在NHibernate项目分层中的应用。因此,您可以在不引用NH的情况下从任何项目注入接口。

Application Specific Base Repository Class

Although you can derive your repositories from NhRepositoryBase of ASP.NET Boilerplate, it's a better practice to create your own base class that extends NhRepositoryBase. Thus, you can add shared/common methods to your repositories easily. Example:

虽然你可以导出你的库从ASP.NET样板nhrepositorybase,创建自己的基类,延伸nhrepositorybase这是一个更好的实践。因此,您可以轻松地将共享/共享方法添加到存储库中。例子:

//Base class for all repositories in my application
public abstract class MyRepositoryBase<TEntity, TPrimaryKey> : NhRepositoryBase<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected MyRepositoryBase(ISessionProvider sessionProvider)
: base(sessionProvider)
{
} //add common methods for all repositories
} //A shortcut for entities those have integer Id.
public abstract class MyRepositoryBase<TEntity> : MyRepositoryBase<TEntity, int>
where TEntity : class, IEntity<int>
{
protected MyRepositoryBase(ISessionProvider sessionProvider)
: base(sessionProvider)
{
} //do not add any method here, add the class above (since this inherits it)
} public class TaskRepository : MyRepositoryBase<Task>, ITaskRepository
{
public TaskRepository(ISessionProvider sessionProvider)
: base(sessionProvider)
{
} //Specific methods for task repository
}

ABP框架系列之三十八:(NHibernate-Integration-NHibernate-集成)的更多相关文章

  1. ABP框架系列之三十四:(Multi-Tenancy-多租户)

    What Is Multi Tenancy? "Software Multitenancy refers to a software architecture in which a sing ...

  2. ABP框架系列之三十二:(Logging-登录)

    Server Side(服务端) ASP.NET Boilerplate uses Castle Windsor's logging facility. It can work with differ ...

  3. ABP框架系列之三十九:(NLayer-Architecture-多层架构)

    Introduction Layering of an application's codebase is a widely accepted technique to help reduce com ...

  4. ABP框架系列之十八:(Data-Transfer-Objects-数据转换对象)

    Data Transfer Objects are used to transfer data between Application Layer and Presentation Layer. 数据 ...

  5. ABP框架系列之四十八:(Specifications-规范)

    Introduction Specification pattern is a particular software design pattern, whereby business rules c ...

  6. ABP框架系列之三十五:(MVC-Controllers-MVC控制器)

    Introduction ASP.NET Boilerplate is integrated to ASP.NET MVC Controllers via Abp.Web.Mvc nuget pack ...

  7. ABP框架系列之三十六:(MVC-Views-MVC视图)

    Introduction ASP.NET Boilerplate is integrated to MVC Views via Abp.Web.Mvc nuget package. You can c ...

  8. ABP框架系列之三十:(Javascript-API-Javascript-API)

    ASP.NET Boilerplate provides a set of objects and functions that are used to make javascript develop ...

  9. ABP框架系列之五十四:(XSRF-CSRF-Protection-跨站请求伪造保护)

    Introduction "Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a maliciou ...

随机推荐

  1. U3D学习12-黑暗之光实例

    1.static勾选后,在scene场景操作后,导致不断烘焙,cpu占用高? 取消自动烘焙 2.UI操作事件 //监听事件增加         mainInputField.onValueChange ...

  2. 如何在idea里面新建一个maven项目,然后在这个maven项目里创建多个子模块

    如何在idea里面配置maven我这里就不多说了 先新建一个maven项目作为总的管理项目 不用勾选什么,直接下一步 这样子一个普通的maven项目就创建成功了. 因为这个项目是用来管理多个子模块的, ...

  3. Vim 命令、操作、快捷键

    打开单个文件:vim file 同时打开多个文件:vim file1 file2 file3 ... 在vim窗口中打开一个新文件 :  :open file 在新窗口中打开文件: :split fi ...

  4. 游戏搭服自动化脚本shell

    #!/bin/bash #;g=6006c= 178pop_s10 rm-bp1gy2r82o607w4v8.mysql.rds.aliyuncs.com # basedir=/data/jzadmi ...

  5. Java中的包装数据类型

    基本类型 包装器类型 boolean Boolean char Character int Integer byte Byte short Short long Long float Float do ...

  6. 初学JSON和AJAX心得透过解惑去学习

    虽然复制代码再改参数,也能正常运作.但是看懂里面语法,就可以客制成适合你自己程序.例如录制Excel巨集,会有一些赘句,这时候整合就是很重要工作. [大纲] 时间分配 AJAX Markdown教学及 ...

  7. Modelsim command line 传参数到 .do 文件

    gui跑mdelsim总觉得很麻烦,使用命令来启动方便了很多,类似linux一样,其实目前windows也可以做到,只是业界不怎么用windows罢了. 基于modelsim搭了一个UVM环境,  用 ...

  8. WMS专业术语&系统功能操作培训

    逻辑层:公司.分部.地区物理层:仓库.1个仓库只能属于思维的1个地区.命名规则:SCPRD_WMWHSE1货主:纳思达多货主:1个仓库可以配置1个或多个货主SKU:物料代码(stock keeping ...

  9. jstl标准标签库 其他标签

    url操作标签 import 将另一个页面的内容引入到这个页面上来, 与include指令的区别: 这个标签可以引入其他项目中甚至网络上的资源 <c:import url="被导入的路 ...

  10. Python设计模式 - UML - 包图(Package Diagram)

    简介 包图是对各个包及包之间关系的描述,展现系统中模块与模块之间的依赖关系.一个包图可以由任何一种UML图组成,可容纳的元素有类.接口.组件.用例和其他包等.包是UML中非常常用的元素,主要作用是分类 ...