![](/img/trans.png)
[英]Fluent nHibernate map HasMany to Entity/Table with no Primary Key
[英]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.