NHibernate 中实体在 HashedSet 中使用的要求

发布于 2024-09-27 10:14:17 字数 242 浏览 2 评论 0原文

我想在 NHibernate 中使用 Iesi.Collections HashedSet 类作为实体集合。我想要的功能是不能添加重复的实体。我希望如果实体共享 Id(即主键)字段,或者如果它们的 Id == 0(即未保存),则将实体视为重复,然后比较某些关键属性。

我注意到默认情况下 HashedSet 似乎使用引用相等来定义重复项。为了让 HashedSet 根据我上面描述的规则定义重复,我需要更改什么? (例如覆盖.Equals、覆盖==等)。

I would like to use the Iesi.Collections HashedSet class for entity collections in NHibernate. The functionality I want is that duplicate entities cannot be added. I would like entities to be considered duplicate if they share the Id (i.e. primary key) field, or, if they have Id == 0 (i.e. unsaved), then certain key properties are compared instead.

I notice that by default the HashedSet appears to define duplicates using reference equality. What do I need to change in order to get the HashedSet to define duplication according to the rules I described above? (E.g. override .Equals, override ==, etc).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飞烟轻若梦 2024-10-04 10:14:17

Equals 和 GetHashCode 必须始终一起重写。 GetHashCode 文档指出:

重写 GetHashCode 的派生类还必须重写 Equals,以保证被视为相等的两个对象具有相同的哈希码;否则,Hashtable 类型可能无法正常工作。

Jon Skeet 对这个问题的回答提供附加信息。

覆盖相等运算符是可选的,但我建议这样做。

Equals and GetHashCode must always be overridden together. The documentation for GetHashCode states:

Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, the Hashtable type might not work correctly.

Jon Skeet's answer to this question provides additional information.

Overriding the equality operators is optional but I recommend it.

一袭水袖舞倾城 2024-10-04 10:14:17

您需要重写 GetHashCode 方法。

You need to override GetHashCode method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文