If you haven't setup a Fluent NHibernate project before, you should checkout the GettingStarted: Introduction guide.
As mentioned in ClassMap, all mappings are done from inside the constructor of a ClassMap<T>
derived class; so baring that in mind, all examples are going to exclude the surrounding class.
This is pretty much the standard Id
that most people use. Mapped as a identity
or autoincrement
in the database, and with a type of int
.
// schema Id int identity(1, 1) primary key // model public int Id { get; private set; } // mapping Id(x => x.Id);
This mapping sees that the Id
property is an int
and makes the assumption that it's an auto-incrementing primary key.
Similarly, if your Id
is a Guid
, then Fluent NHibernate uses the NHibernate guid.comb
generator, and a string
defaults to assigned
.
You may want to use a different name for the property in your model than what's in your database, here's how to map it:
// schema some_ugly_id int identity(1, 1) primary key // model public int Id { get; private set; } // mapping Id(x => x.Id) .ColumnName("some_ugly_id");
You may need to explicitly change what Fluent NHibernate uses as the identity generator; this could be if your Id
is an int
but you don't want it to be an auto-incrementing identity.
Id(x => x.Id) .GeneratedBy.Sequence("uuid_sequence");
You can use the GeneratedBy
property to specify various different generators for the Id
.
Currently GeneratedBy
supports: Identity
, Increment
, specifying a Sequence
, HiLo
and SeqHiLo
, UuidHex
and UuidString
, Guid
and GuidComb
, Assigned
, specifying a Foreign
identifier, and Native
.
An Exception
will be thrown if you try to use a generator with a type that isn't compatible, for example if you use guid
with an int
property.
If your domain stipulates that you must have a special unsaved value, then you can map it like so:
Id(x => x.Id) .WithUnsavedValue(-1);
If your entity uses a backing field for a property, or some other non-standard design, then you can map it using the Access
property.
// schema Id int identity(1, 1) primary key // model private int _id; public int Id { get { return _id; } } // mapping Id(x => x.Id) .Access.AsCamelCaseField();
The Access
property can be used to set various combinations of Field
and Property
, with various casings and prefixes.
For example, for the same mapping but with the field called _id
you could use the Prefix.Underscore
overload: Access.AsCamelCaseField(Prefix.Underscore)
.