Search code examples
c#nhibernateormfluent-nhibernatenhibernate-mapping

NHibernate - Add Comment Property to Entities (Store with Join)


I have a system where I need to be able to add a Comment field onto Customer and Location models but I cannot touch the schema of the existing tables. However, I can add a Comments table. I have simplified this example. We would like the ability to add this Comment to more models moving forward they all use a Guid as Id.

This existing system is a 3rd party system with its own data access layer.

We are just starting to get into NHibernate. From what I can tell it looks like a Join map.

Example:

public class Customer 
{
    public Guid Id { get; private set; }
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public string Comment { get; set; }
}    

public class Location
{
    public Guid Id { get; private set; }
    public string Name { get; private set; }
    public string Address { get; private set; }
    public string Comment { get; set; }
}

Note: we are sure we want the Comment as a 1-to-1 relationship and not a 1-to-many.

How do I configure a separate table just capture Id and Comment? I'm looking for the right terminology to use. I'm looking for examples with XML (and if possible Fluent config). I would like to keep the Comments for all objects in one table. Thanks.


Solution

  • If you can add Comment table (and corresponding key columns in the existing tables) than fluent mapping can look like

    public class CustomerMap : ClassMap<Customer>{
      public CustomerMap(){
            //...other columns mappings
    
            References(c=>c.Comment).Column("CommentId");
      }
    }
    

    And repeat it for other entities as well. You can set desired fetch-mode(join) and other action there as well. I have wrote References there (so many-to-one) but if you need one-to-one mapping it is not a big difference