NHibernate、非复合 ID 和 GetHashCode
当我的域模型在数据库中有复合键时,如果忘记覆盖 Equals/GetHashCode,我会收到异常。
NHibernate.MappingException: composite-id class must override Equals():
为什么当我有非复合 ID 时,它不会给出相同的错误?
When my domain model have a composite key in the database I will get an exception when forgetting to override Equals/GetHashCode
NHibernate.MappingException: composite-id class must override Equals():
Why does it not give me the same error when I have a non composite ID?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NHibernate 在其内部状态跟踪引擎中使用类的主键值来识别该实例。
当您的域中有单个主键属性时,NHibernate 将使用该属性返回的值作为键值,使用该值调用
GetHashcode
和Equals
主键就像您在Dictionary
实例中使用它一样。当有多个主键属性形成复合键时,NHibernate 没有简单的方法来获取它可以使用的键值。它要求您定义如何确定两个实例之间的相等性,从而有效地将实例转换为自己的密钥,就像在
HashSet
中一样。如果您尚未重写类型上的
Equals
和GetHashCode
来使用复合键值,则它不会反映数据模型使用的“相等”(两行如果它们具有相同的主键,则相等)并且 NHibernate 无法确定它正在跟踪正确的实体;这就是异常发生的原因。您可以找到复合键的概述以及有关处理它们的巧妙方法的更多信息 此处。
NHibernate uses the primary key value of your class in its internal state-tracking engine to identify that instance.
When you have a single primary key property in your domain, NHibernate will use the value returned by the property as the key value, calling
GetHashcode
andEquals
on the value, using the primary key much like you would use it in aDictionary<TKey,TValue>
instance.When there are multiple primary key properties forming a composite key, NHibernate has no trivial way to get a key value it can use. It requires you define how to determine equality between two instances, effectively turning the instance into its own key much like it would be in a
HashSet<T>
.If you haven't overridden
Equals
andGetHashCode
on your type to use your composite key values, it does not reflect the "equality" used by the data-model (two rows being equal if they have the same primary key) and NHibernate cannot be certain it is tracking the correct entities; this is why the exception occurs.You can find out an overview of composite keys and more information on clever ways to deal with them here.