Fluent NHibernate
Auto Mapping Altering Entities (changes)

Showing changes from revision #2 to #3: Added | Removed

Continuing with the same schema we used in Auto Mapping Type Conventions, we now 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 ana ITypeConventionconvention.

So how exactly do you supply alterations only for a specific entity? Easy! with ForTypesThatDeriveFrom<T>(ClassMap<T>).


.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.