![](/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.