tags:

views:

209

answers:

1

Can I use pivot tables with NHibernate?

Can I write ID id = new Transaction().GetNextID("[TableName]", "[IDColumnName]")-like codes to increment IDs with NHibernate?

+2  A: 

Auto Increment Ids
There are auto-increment id generators available for all databases supported by NHibernate. See generator in the reference documentation.

To use an auto-increment Id property, map it as follows and leave the Id value as the default (0) when creating new entities.

<id name="Id" >
    <generator class="native"/>
</id>

You can even roll your own generator by implementing NHibernate.Id.IIdentifierGenerator. However, see this question for a discussion on why you should use the database native auto-increment mechanism.

Pivot Tables
NHibernate has no specific support for Pivot tables. That said, you can map the results of any SQL query to objects using a result transformer. The target object does not need to be mapped, and the columns must match the properties.

Named SQL queries can be defined in your mapping files. You can also use native SQL queries directly. Both types of query support named and positional parameters.

var list = session.GetNamedQuery("query-name")
    .SetResultTransformer( Transformers.AliasToBean<Foo>())
    .SetString("name", "foo")
    .List<Foo>();

var list = session.CreateSQLQuery("SELECT * FROM table WHERE A=? and B=?")
    .SetString(0, "foo")
    .SetInt(1, 42)
    .SetResultTransformer( Transformers.AliasToBean<Foo>())
    .List<Foo>();

If you defined a view for a pivot query, you could define a readonly mapped class for it with mutable="false".

Result Transformers

A number of result transformers are available, including:

  • Transformers.ToList Returns a list of values for each row.
  • Transformers.AliasToEntityMap Creates a map from column names to values for each row.
  • Transformers.AliasToBean() Creates an object of the nominated type per row and sets its properties with the value from the column of the same name.
Lachlan Roche
You don't even need a named query (which is good practice, but looks like overhead to a noob), you just can execute any SQL query directly.
Stefan Steinegger