簡體   English   中英

將值對象映射為 fluent nhibernate 中的主鍵

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

我在 fluent-nhibernate 中映射我的類ProcessingCode 它有一個屬性Code ,它是一個 ValueObject。 如何將其映射為主鍵?

這是我將它映射為不作為主鍵的方式:

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

以下是與映射相關的類:

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方法用於將值對象映射為類的常規屬性。 有兩種映射 ID 的方法: Id映射常規類型和CompositeId映射組件。 因此,答案是使用CompositeId而不是Component來實現“簡單”的解決方案:

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

或者,您可以實現自定義IUserType

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM