Saturday, February 12, 2011

nHibernate, can I map to a table that doesn't have an row-per-object mapping?

I have a database that contains a table that looks a bit like this:

PropertyId, EntityId, Value

PropertyId and EntityId are a combined primary key. Every Entity is spread over a couple of rows where every row contains a single property of the entity. I have no control over this database so I'll have to work with it.

Is it possible to use NHibernate to map entities from this table to single objects? I only have to read from this table, this might make things a bit easier. Or would I be better off just using DataReaders and do the mapping myself?

  • Hi,

    Not quite done that, but you could use a custom SQL query to define your entities (distinct entityid, plus any entity level attributes), see here .

    Although I can see you might want the property/values mapped to attributes of the entity object. Which might mean further queries to populate them by hand - which may mean your data reader route is best.

    If your happy for them to be a collection of the entity then that should be no problem.

    Mendelt : Thanks. I'll try it out. I can store the properties in a list and make them available to the outside world through individual property getters that look up the right property in the list. Not ideal but workable :-)
  • I can't remember the exact syntax, but a map would do it:

    <map name='Values' table='EntityPropertyValue'>
      <key column='EntityId'  />
      <index-many-to-many class='Person' column='PersonId' />
      <element column='Value' type='object' />
    </map>
    
    From David Kemp

0 comments:

Post a Comment