I have a view that I am going to only read from (no writes). This view does not have any unique key (not event composite).
So how can I map this view in NHibernate without touching the view? I do not want to add a new column to the view to generate a unique identity for me. Is there a way to map this view and generate the identity column on the NHibernate side?
I can generate a GUID in my entity class like:
public class MyViewClass
{
private Guid _id = new Guid();
public virtual Guid Id { get { return _id; } set { _id = value; } }
}
But how can I make the mapping work? The following code does not work:
public class MyViewClass: ClassMapping<MyViewClass>
{
public MyViewClass()
{
Mutable(false);
Id(x => x.Id, m => m.Generator(Generators.Guid));
}
}
It expects to have the Id column in view and throws:
System.Data.SqlClient.SqlException: Invalid column name 'Id'.
BTW, I am using NHibernate 3.2 and mapping by code.
From what I understand, NHibernate needs an Id column to be able to map a view to the entity. So to fulfill this requirement, there are 2 ways:
In the mapping class I also needed to add
SchemaAction(.)
, otherwise NHibernate will complain on runtime that it cannot map the entity to a table/view.The mapping class would look like this (Either choose option 1 or 2):
I also prefer mapping the view to an entity because then I can use QueryOver or Query (LINQ) API to eliminate the use of magic strings (table/column names) in a normal SQL query.