流暢的 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
方法用於對映其他列。