[英]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?如何将其映射为主键?
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
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.