Dale K
Dale K

Reputation: 27462

nhibernate: Class Mapping with no table

I have an entity class that I use to represent the results of a SQL query. The mapping for the class is shown below. Yet as far as I can tell nhiberate treats the mapping as if there is a real database table - when in fact there is not. In this case there is nothing in the database that represents this entity at all. I am using this to map a query through, but the same would be true of a view. Is there no way to indicate to nhibernate that there isn't a table represented by the mapping?

<class name="Models.UserTransaction"> <!-- Defaults table name same as Entity even though table doesn’t exist -->
  <id name="Id">
    <column name="Id" not-null="true" unique="true" />
    <generator class="native" />
  </id>
  <property name="TransType" />
  <property name="Date" />
  <property name="Amount" />
  <property name="Balance" />
</class>

This is the query I am mapping, which uses a user defined table. I couldn't get it working without having a mapping even though the example I copied appeared to.

  <sql-query name="UserTransactions">
    <query-param name="userId" type="string" />
    <return class="Models.UserTransaction" alias="userTx">
      <return-property name="TransType" column="TransType" />
      <return-property name="Id" column="Id" />
      <return-property name="Date" column="TransDate" />
      <return-property name="Amount" column="Amount" />
      <return-property name="Balance" column="Balance" />
    </return>
    <![CDATA[
      SELECT userTx.[Type] as TransType, userTx.[Id] as Id, userTx.[Date] as TransDate, userTx.[Amount] as Amount, userTx.[Balance] as Balance
      FROM dbo.User_AccountStatement(:userId) userTx
    ]]>
  </sql-query>

Upvotes: 2

Views: 2562

Answers (2)

Fran
Fran

Reputation: 6530

If you have a db view, you can use nhibernate to map to that, but if all you are doing is storing the projection fields of the query there doesn't need to be a map at all.

How are you querying this data?

if you are using the criteria API, you can use the resultstransformer to map the returned object array to your class. the types have to match between your class that the projection.

If you are using the LINQ provider you can project directly into your class. so you'd have something like this

from s in Session.Query<some-type>
where s.some-property== "some-value"
select new your-type
{
some-property-on-your-type = s.some-property,
some-other-property-on-your-type = s.some-other-property
}

There is no need to write a mapping to the database since you aren't mapping to an object in the database.

Upvotes: 1

jbl
jbl

Reputation: 15433

I guess you should at least specify a view as the tablename of your mapping. The view should have the same resulting columns as your query (and hopefully return any row that your query could return)

Then you will be able to :

Upvotes: 0

Related Questions