流畅的 NHibernate 映射
该 Fluent NHibernate
是一个库,以帮助你在使用 C#代码,而不是 XML 映射的实体映射。流畅的 NHibernate 使用 fluent pattern
,它基于创建映射的约定,它为你提供了可视工作室工具(如 intellisense)的强大功能,以改善你映射实体的方式。
在项目中添加 Nuget 的 Fluent NHibernate 引用,并添加一个 CustomerMap.cs 类:
namespace Project.Mappings
{
public class CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
Table("CUSTOMERS");
Id(x => x.Id).Column("Customer_Id").GeneratedBy.Native();
//map a property while specifying the max-length as well as setting
//it as not nullable. Will result in the backing column having
//these characteristics, but this will not be enforced in the model!
Map(x => x.Name)
.Length(16)
.Not.Nullable();
Map(x => x.Sex);
Map(x => x.Weight);
Map(x => x.Active);
//Map a property while specifying the name of the column in the database
Map(x => x.Birthday, "BIRTHDAY");
//Maps a many-to-one relationship
References(x => x.Company);
//Maps a one-to-many relationship, while also defining which
//column to use as key in the foreign table.
HasMany(x => x.Orders).KeyColumn("CustomerPk");
}
}
}
CustomerMap
类来自 ClassMap<T>
,它是映射的基类,包含创建 T
实体映射所需的所有方法。Table
方法定义了你要映射的表名。Id
方法用于映射 primery key
列。Map
方法用于映射其他列。