Some O/RMs do their mapping based on attributes. LINQ to SQL and Entity Framework are good examples, although Entity Framework also supports mapping by code. I'm not saying this is good or bad - some people think it "pollutes" POCOs, other think it makes them easier to understand -, but, likewise, NHibernate also allows to map entities by attributes, let's see how.
First, add a reference to the NHibernate.Mapping.Attributes NuGet package:
Next, go to your entity and start adding some attributes:
Basically, you will use:
- ClassAttribute for marking a class as an entity;
- IdAttribute: for declaring the id property;
- GeneratorAttribute: for the id generator strategy;
- PropertyAttribute: a mapped property;
- BagAttribute/ListAttribute/SetAttribute/ArrayAttribute/etc: kinds of collections;
- KeyAttribute: the key in a relation;
- ElementAttribute: an element of an indexed collection;
- IndexAttribute: the index in an indexed collection;
- OneToManyAttribute/ManyToOneAttribute/OneToOneAttribute/ManyToManyAttribute: an endpoint property.
All these attributes live in the NHibernate.Mapping.Attributes namespace and are named very closely to the equivalent HBM.XML elements, which means they must be ordered (notice the first number on some attributes). Now, in order to actually make sense of these attributes, you need to:
And that's all it takes! Have fun!