NHibernate - Wrong Thinking? Join Subclass Model
I have a simple model class (Part) that pulls information from it from one table (t_Part).
I need a subclass of this model called (ProducedPart), which will still use NHibernate's caching mechanisms, but will only be instances (Part) that have a foreign key relationship in a table called "t_PartProduction". I don't need to have a model for this second table.
I only need the read-only version of ProducPart
I could always implement Facade / Repository on this, but I was hoping to set up a mapping that would pull "t_Part" along with "PartProduction" when I asked for "ProducedPart" in NH.
Is this the wrong way to use NH?
Edit
So the SQL would look like
SELECT p.*
FROM t_Part p
INNER JOIN t_PartProduction pp ON pp.PartID = p.PartID
WHERE pp.ProductionYear = '2009'
a source to share
The key here is using elements where
and mutable
definitions class
for NHibernate mappings.
Using Fluent NHibernate it looks like this:
public Part()
{
WithTable("t_Part");
Id(i => i.Id).ColumnName("PartID");
Map(m => m.Name).ColumnName("Part");
SetAttribute("where", "PartID IN ( SELECT pp.PartID FROM t_PartProduction pp WHERE pp.ProductionYear = '2009' ) ");
ReadOnly();
}
a source to share
No, itβs quite possible. Look in the NHibernate documentation for the table per subclass inheritance model. It actually implements this as a LEFT JOIN, so that when you load a Part, it instantiates your Part or your ProducedPart depending on the presence of another string. You will find documentation at nhibernate.info .
I'm not sure if you could make ProducedPart read-only, but do it.
I guess from this:
WHERE pp.ProductionYear = '2009'
what do you want this subclass to be only if the release year is 2009 i.e. if there is a t_PartProduction entry in the t_PartProduction record for a year, you want that part to be treated as a simple Part object and not a ProducedPart, then you might consider creating a view definition in your database that is a filtered version of t_PartProduction, and then adds your subclass to that view, not the base table.
a source to share
I believe you are looking for a combined subclass. In FNH it will look something like this:
public class PartMap : ClassMap<Part>
{
public PartMap()
{
Id(x => x.Id)
JoinedSubClass<ProducedPart>("PartID", sub => {
sub.Map(x => x.Name);
sub.Map(x => x.ProductionYear);
});
}
}
For NHibernate to cache the results, you will need to map the subclass (and if you haven't mapped it, you won't be able to get NH to load it in the first place).
Quoting in some context from the FNH groups stream , it obviously won't be read-only. In my opinion, doing read-only things is not good for managing NHibernate. This is better controlled by the database and connections (i.e. creates a connection to a database that only has SELECT permissions to access tables / views). Check out my answer to a previous SO question on read-only sessions in NHibernate for most of my thoughts on this.
a source to share