简体   繁体   English

将值对象映射为 fluent nhibernate 中的主键

[英]Map value object as primary key in fluent nhibernate

I am mapping my class ProcessingCode in fluent-nhibernate.我在 fluent-nhibernate 中映射我的类ProcessingCode It has a property Code which is a ValueObject.它有一个属性Code ,它是一个 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();
    }
}

Component method is used to map a value object as a regular property of the a class. Component方法用于将值对象映射为类的常规属性。 There are two methods to map IDs: Id to map a regular types and CompositeId to map components.有两种映射 ID 的方法: Id映射常规类型和CompositeId映射组件。 So, the answer is to use CompositeId instead of Component for an "easy" solution:因此,答案是使用CompositeId而不是Component来实现“简单”的解决方案:

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 .或者,您可以实现自定义IUserType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM