Search code examples
c#nhibernatefluent-nhibernatenhibernate-mappingfluent-nhibernate-mapping

NHibernate - Mapping abstract immutable value object


I have following domain model that I need to persist in database with help of Fluent NHibernate:

public class Entity
{
    public Guid Id { get; set; }
    public IValueObject AnyValueObject { get; set; }
}

public interface IValueObject
{
    string Value { get; }
}

public class ValueObject : IValueObject
{
    private readonly string _value;

    public ValueObject(string value)
    {
        _value = value; // null checks omitted for brevity
    }

    public string Value { get { return _value; }}
}

public class AnotherValueObject : IValueObject
{
    private readonly string _value;
    private readonly string _anotherValue;

    public AnotherValueObject(string value, string anotherValue)
    {
        _value = value; // null checks omitted for brevity
        _anotherValue = anotherValue;
    }

    public string Value { get { return _value; } }
    public string AnotherValue { get { return _anotherValue; } }
}

ValueObject and AnotherValueObject doesn't have any id and they're immutable.

The problem is that I have no idea how to write map for AnyValueObject property. I know that value objects must be mapped as Components, but how to deal with abstract immutable value objects?


Solution

  • You either have to give it an ID or avoid polymorphism, because NH doesn't support polymorphism for components and requires an ID for entities.

    If it is a rather simple inheritance with just a few different classes and no logic, I would put it all in the same class. It much simpler anyway. Then you ca map it as a component. You could give it an enum to easily check the type it has.

    If you really (really) need inheritance / polymorphism, you need to give it an ID.