Danicco
Danicco

Reputation: 1673

NHibernate programmatically mapping

I want to create a custom mapping standard so I don't have to create the map.cs file for all new classes in the project.

public class Person
{
    public int PersonID { get; set; }
    public string Name { get; set; }
}

Usually I'd have this:

public class PersonMap : ClassMapping<Person>
{
    public PersonMap()
    {
        Table("Person");

        Id(p => p.PersonID, map => 
        {
            map.Column("PersonID");
            map.Generator(Generators.Identity);
        });

        Property(p => p.Name, map => map.Column("Name"));
    }
}

I'd like to dynamically create these mappings based on some standards using reflection.

public class GenericDAL<T> where T : class, new()
{
    public GenericDAL() 
    {
        Configuration hConfig = new Configuration();
        hConfig.DatabaseIntegration(c =>
        {
            c.ConnectionStringName = "myConnectionStringName";
            c.Dialect<MsSql2012Dialect>();
        });

        ModelMapper mapper = new ModelMapper();
        //Dynamic Mapping here

        ISessionFactory _sessionFactory = hConfig.BuildSessionFactory();
    }
}

I don't know how I can create a new ClassMapping from my T, how can I do this?

Upvotes: 2

Views: 5432

Answers (2)

Firo
Firo

Reputation: 30813

@SteveLillis already answered the question in the comments that there are already solutions for this.

Both MappingByCode in NHibernate (see below) and FluentNHibernate support automapping with conventions and overrides.

Links for Mapping By Code copied from original Answer which is not available anymore

  1. First impressions
  2. Naming convention resembling Fluent
  3. Property
  4. Component
  5. ManyToOne
  6. inheritance
  7. dynamic component
  8. Set and Bag
  9. OneToMany and other collection-based relation types
  10. concurrency
  11. OneToOne
  12. Join
  13. Any
  14. List, Array, IdBag
  15. Map
  16. Id, NaturalId
  17. composite identifiers
  18. entity-level mappings
  19. the summary

Upvotes: 3

Peter C Santana
Peter C Santana

Reputation: 1

I was looking for the same thing and I found a great documentation on NHibernate official website.

Here we have all the links to "fabiomaulo.blogspot" website, there you will find what are you looking for, WITHOUT FluentNHibernate.

Good Luck

Upvotes: 0

Related Questions