Fluent NHibernate fetching view without unique identifier

前提是你 提交于 2020-01-02 01:09:32

问题


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");
    }
}

回答1:


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);
    [...]
}



回答2:


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. "



来源:https://stackoverflow.com/questions/2920378/fluent-nhibernate-fetching-view-without-unique-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!