作者:手机用户2502892403 | 来源:互联网 | 2023-09-01 16:53
ImusingNHibernatetopersistmyItemclasstoaSQLdatabase.TheItemclasshasapropertyItem.
I'm using NHibernate to persist my Item
class to a SQL database. The Item
class has a property Item.Tags
of type ICollection
which I am mapping using the following NHibernate configation.
我正在使用NHibernate将我的Item类持久化到SQL数据库。 Item类有一个ICollection
类型的属性Item.Tags,我使用以下NHibernate配置进行映射。
Also here's my mapping for my Tag class, which simply has an int ID and a string name.
这里也是我的Tag类的映射,它只有一个int ID和一个字符串名称。
This all works fine, yet it allows duplicate tags to be created with the same name. Thus the code below will create three separate "foo" entries in the Tags table all with separate IDs.
这一切都很好,但它允许使用相同的名称创建重复的标签。因此,下面的代码将在Tags表中创建三个单独的“foo”条目,所有条目都具有单独的ID。
myItem1.Tags.Add(new Tag("Foo"));
myItem2.Tags.Add(new Tag("Foo"));
myItem3.Tags.Add(new Tag("Foo"));
This is obviously not how I want this to work. I could add a unique constraint to the Tags.Name column, but then the code above would only thrown an exception.
这显然不是我希望这个工作的方式。我可以为Tags.Name列添加一个唯一的约束,但是上面的代码只会抛出异常。
On the object model side I want to be able to simply add and remove tags from an Item
by editing a collection of Tag
or String
. However, when my items are persisted to the database it should figure out what new tags need to be created and when it should be mapping to existing entries in the Tags table.
在对象模型方面,我希望能够通过编辑Tag或String的集合来简单地添加和删除Item中的标签。但是,当我的项目持久化到数据库时,它应该确定需要创建哪些新标记以及何时应该映射到Tags表中的现有条目。
I've also considered changing this to a value based one-to-many relationship where Item.Tags
would simply be a IList
and would map to a single Tags table with entries for every individual tag on every Item
. This would work as well, but I think I would prefer the first, as it would make finding items with a specific tag more efficient. I'm pretty new to relational databases as well. So I'm not even sure if this should be a concern.
我还考虑将其更改为基于值的一对多关系,其中Item.Tags将只是一个IList
,并将映射到单个Tags表,其中包含每个Item上每个单独标记的条目。这也可以,但我认为我更喜欢第一个,因为这样可以更有效地查找具有特定标签的项目。我对关系数据库也很陌生。所以我甚至不确定这是否应该引起关注。
2 个解决方案