Search code examples
collectionsfluent-nhibernateone-to-manyrelationshipautomapping

fluent NHibernate automapping


Please, how can I do map a property of type one-to-many in fluent NHibernate through AutoMapping?

My entities are mapped like down there: enter image description here


Solution

  • There are two ways:

    • TipoContato should have IList<Contato> (or ICollection<Contato>) property
    • or Contato should have TipoContato property

    Both ways automapping should handle everything correctly, assuming that you either change the name of column with foreign key in Contacto table to TipoContacto_id or provide your own foreign key naming convention to skip the default underscore - see more about conventions on Fluent NHibernate manual.

    If you want to have different relation in object model, i.e. two-way, you'll need to define it manually in automapping override using HasMany with Inverse on TipoContato side and References on Contato side.

    Anyway, if you have modelled your database first, it can be harder to use automapping and it will probably need a lot of overrides. You should either make your object model first and use automapping, or make your database first and prepare mappings manually.