Fluent NHibernate: Auto Mapping Entity Conventions
Notice: The content in this post is out of date, please refer to the Auto Mapping page in the Fluent NHibernate Wiki for the latest version.
This post should be short and sweet. We want to alter our has many relationship from Shelf
to Product
so that it has a cascade set on it. We don’t want this to affect all one-to-many’s in our domain, so we need to do this alteration only on the Shelf
entity rather than with an ITypeConvention
.
So how exactly do you supply conventions only for a specific entity? Easy! with ForTypesThatDeriveFrom<T>(ClassMap<T>)
.
autoMappings
.WithConvention(convention =>
{
// our conventions
})
.ForTypesThatDeriveFrom<Shelf>(map =>
{
map.HasMany<Product>()
.Cascade.All();
});
The ForTypesThatDeriveFrom
method takes a generic parameter that’s the entity you want to customise. The parameter is an expression that allows you to alter the underlying ClassMap<T>
that is generated by the auto mapper. Anything you can do in the non-auto fluent mapping, you can do in this override. So for our case, we map a HasMany
of Product
, and specify it’s cascade; this overrides the HasMany
that will have been generated by the auto mapper.
That’s it. We’ve overridden the auto mapping explicitly for a specific type, while not affecting the general conventions of the system. You can do this for as many types as you need in your domain; however, baring in mind readability, it may sometimes be more appropriate to map entities explicitly using the standard fluent mapping if you find yourself overriding a lot of conventions.