views:

62

answers:

2

I have document scanning system where several types of documents are scanned. Initially, the document has no information when its scanned, then they get classified and additional information is entered for them in a second step later. So, I have a base class called Document, and subclasses for each type with their respective metadata like below. I have it setup as a table-per-subclass (joined subclass) mapping in NHibernate.

public class Document
{
   public int ID { get; set; }
   public string FilePath { get; set; }
}

public class Certificate : Document
{
   // certificate-specific fields
}

public class Correspondence : Document
{
   // correspondence-specific fields
}

What I need to be able to do is create a Document class first and save it. Then retrieve in a second step later on and convert it to one of the subclass types and fill in the rest of its information. What would be the best approach to do this, and is this even possible with NHibernate? If at all possible I would like to retain the original document record, but its not a dealbreaker if I have to jettison it.

+2  A: 

Unfortunately, NHibernate does not allow you to switch between subclasses after initial creation; to get this working the way you want, you have 3 options:

  1. Use a native sql call to change the discriminator (and possibly) add or change any subclass-related fields.
  2. Copy the contents of your object to a new object of the proper class and then delete the original.
  3. Don't use subclasses, control the state of your object through an enumeration or some other mechanism that allows you to determine their type at run-time.
DanP
+2  A: 

This issue has already been discussed here. I would go with Terry Wilcox's tip to use a role for this. Composition over inheritance.

zoidbeck
Great example; missed that article +1
DanP