The object-relational mapper for .NET

Automatic Mapping: Pluralize table names

Note: this is a cross post from my own blog.

In this post we done some effort in automatically generate the mapping based on convention, but we miss a very common one: table names is usually the pluralized entity name. This is usually done by using an inflector. Thanks to Stack Overflow, I found this question about it, and choose that one, that is a single easily embeddable file. So we modify a little our AutoMapper class as below:

void AutoMapper_BeforeMapClass(IModelInspector modelInspector, Type type, IClassAttributesMapper classCustomizer)
           // Create the column name as "c"+EntityName+"Id"
           classCustomizer.Id(k => 
                                   k.Generator(Generators.Native); k.Column("c" + type.Name + "Id"); 


And this is all, the generated mapping will change as:

<hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x=""
sd="http://www.w3.org/2001/XMLSchema" namespace="MappingByCode" assembly="Mappin
gByCode" xmlns="urn:nhibernate-mapping-2.2">
  <class name="SimpleEntity" table="SimpleEntities">
    <id name="Id" column="cSimpleEntityId" type="Int32">
      <generator class="native" />
    <property name="Description">
      <column name="txtSimpleEntityDescr" sql-type="AnsiString" />
    <many-to-one name="Referred" column="cReferredId" />

Just for better sharing, I published this “laboratory” project here.

Posted Sun, 04 September 2011 10:28:00 PM by felicepollano
Filed under: mapping, mapping by code

comments powered by Disqus
© NHibernate Community 2022