The Fluent NHibernate
is a library to help you to map the entities using C# code instead of xml mappings. Fluent NHibernate uses the fluent pattern
and it is based on conventions to create the mappings and it gives you the power of the visual studio tools (such as intellisense) to improve the way you map your entities.
Add the reference of the Fluent NHibernate from Nuget on your project and add a class 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");
}
}
}
The CustomerMap
class inhirits from ClassMap<T>
that is the base class for mapping and contains all methods necessary to create the map of your T
entity. The method Table
define the table name you are mapping. The Id
method is used to map the primery key
column. The Map
method is used to map other columns.