Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate fetching view without unique identifier

I'm trying to map a view without an identifier, but nhibernate still generates a sql with the id column (giving me a sql error, since the ID column does not exists in the db). Maybe I'm misunderstanding the Id() constructor?

constructor comments:

Create an Id that doesn't have a corresponding property in the domain object, or a column in the database. This is mainly for use with read-only access and/or views. Defaults to an int identity with an "increment" generator.

public class PersonMapping : ClassMap<Person>
{
    public PersonMapping()
    {
        Table("person");
        ReadOnly();

        Id();
        Map(f => f.Name, "name");
    }
}
like image 614
Wyass Avatar asked May 27 '10 10:05

Wyass


2 Answers

NHibernate requires an ID. The method doc says it creates an ID which has no corresponding property in your domain object - however the database still has an ID.

If you have no field in your table to mark as an identifier (has to be unique..) maybe you can try to identify some columns which can be composed as an composite id.

Given for example a simple link table which links some int to an other int like

A | B
-----
1 | 2
1 | 3
2 | 2

you could use Composite ID as long as all A/B combinations are unique.

public PersonMapping()
{
    [...]
     CompositeId()
         .KeyProperty(x => x.A)
         .KeyProperty(x => x.B);
    [...]
}
like image 199
Zebi Avatar answered Oct 18 '22 03:10

Zebi


You could retrieve the records as value objects (non-managed entities) instead of entities.

"14.1.5. Returning non-managed entities

It is possible to apply an IResultTransformer to native sql queries. Allowing it to e.g. return non-managed entities.

sess.CreateSQLQuery("SELECT NAME, BIRTHDATE FROM CATS")
    .SetResultTransformer(Transformers.AliasToBean(typeof(CatDTO)))

This query specified:

  • the SQL query string
  • a result transformer

The above query will return a list of CatDTO which has been instantiated and injected the values of NAME and BIRTHNAME into its corresponding properties or fields. "

like image 44
J Fernandes Avatar answered Oct 18 '22 03:10

J Fernandes