nhibernate mapping bycode examples

Nov 21, 2012 00:00 · 279 words · 2 minute read ASP.NET Programming

What is Nhibernate mapping by code ?

mapping-by-code is a new feature which come with Nhibernate 3.2 . it is base on Conform library and tries to avoid xml tag in mapping the objects to database tables. the naming convention are similar to XML elements . the first parameter stands for mapped propery and the second one is for corresponding XML attributes.


I am suppose that we have below DTO which we try to map it to tbl1 tables columns.

MyDTO code

public class MyDTO {
 public virtual int IdField { get; set; }
public virtual string Namefield { get; set; }

How to map a table with primary key ?

map a table with primary keyC#

public class MyDTOToTableMapper:ClassMapping<MyDTO> {
 public MyDTOToTableMapper() {
		Id(x => x.IdField, map =>{map.Column("ID");});
		Property(x => x.nameField, map => {map.Column("name");
  • Schema : name of the database is “prefix”
  • Table :Name of table is “tbl1″
  • Id : mapping the “IdField” in ”MyDTO” to “ID” column in “tbl1″ which is our primary key.
  • property: mapping the simple field in MyDTO (nameField) to our table column (name).

How to map a table with unique key ?

mapping unique key to fieldC#

Property(x => x.field2, map => { map.Column("col2");
  • field2: name of our field in MyDTO that want to pass to database
  • col2: name of our column in database
  • map.unique: by setting it to “true” we set unique constraint in col2 table column

How to map a table with composite key ?

mapping composite key to tableC#

ComposedId( map => { map.Property(x => x.col1);
                      map.Property(x => x.col2);
  • col1 and col2 are the column names that we have in database.