0

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?

Vladimir Almaev
  • 2,358
  • 1
  • 28
  • 38

1 Answers1

2

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.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • Putting all in same class is simpler only from persistence perspective but not from domain perspective. And in my case it isn't possible. Consider classic OOP sample with shapes: you have IShape interface with only Area getter and two immutable classes (Rectangle and Round) that implement it. You can't combine rectangles and rounds into one class. – Vladimir Almaev Feb 03 '14 at 14:25