1
votes

I am mapping my class ProcessingCode in fluent-nhibernate. It has a property Code which is a ValueObject. How can I map it as a primary key?

Here is how I am mapping it not as a primary key:

public class ProcessingCodeMap : ClassMap<ProcessingCode>
{
    public ProcessingCodeMap()
    {
        Component(x => x.Code, p => p.Map(x => x.Value).Not.Nullable());
        ... other properties
    }
}

Here are the classes that are relevant for the mapping:

public class ProcessingCode
{
    public virtual Code Code { get; set; }

    //Other properties...
}

public class Code : IEquatable<Code>
{
    public Code()
    {

    }

    public Code(string value)
    {
        Value = value;
    }

    public string Value { get; set; }

    //Some other methods

    public static implicit operator string(Code code)
    {
        if (code == null)
            return null;

        return code.Value;
    }

    public static implicit operator Code(string value)
    {
        return new Code(value);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Code)obj);
    }

    public bool Equals(Code other)
    {
        return string.Equals(Value, other.Value);
    }

    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }
}
1
Could you show the code for classes ProcessingCode? - Suhas
@Suhas I added the relevant code :) - Jakob

1 Answers

0
votes

Component method is used to map a value object as a regular property of the a class. There are two methods to map IDs: Id to map a regular types and CompositeId to map components. So, the answer is to use CompositeId instead of Component for an "easy" solution:

public class ProcessingCodeMap : ClassMap<ProcessingCode>
{
    public ProcessingCodeMap()
    {
        CompositeId(x => x.Code, p => p.KeyProperty(x => x.Value));
        //... other properties
    }
}

Or alternatively you can implement custom IUserType.