nHibernate 为多对多关系添加新项目
我的音乐相关数据库中有三个实体:视频、专辑和流派。视频和专辑都可以有多种类型,因此我通过一个通用表将它们与多对多关联进行链接。 这就是我在数据库中遇到的问题:
Videos: Id (int)
Albums: Id (int)
Genre: Id (int)
Item_Genres: (table for many-to-many mapping)
Id (int)
objectType (here I have "album" for albums and "video" for videos)
objectId (id from either Albums or Videos table)
genreId (Id of the appropriate genre)
我在向我的视频添加新的流派时遇到问题。 当我执行此操作时,
videos.Genres.Add(genre);
nHibernate 在 Item_Genres 表中创建一行,其中包含正确的 genreId 和 objectId,但 objectType 为空。我该如何解决这个问题?
这是我对 Video 类的映射:
<set name="Genres" table="item_genres" lazy="true" where="objectType = 'video'">
<key>
<column name="objectId" not-null="true"/>
</key>
<many-to-many class="Repositories.Entities.Genre">
<column name="genreId" not-null="true"/>
</many-to-many>
</set>
有了它,我可以从数据库请求Video的流派,没有任何问题,问题只在于添加新的。
I have three entities in my music-related DB: Video, Album and Genre. Both videos and albums can have multiple genres, so I'm linking them with many-to-many association via a common table.
That's what I have in DB:
Videos: Id (int)
Albums: Id (int)
Genre: Id (int)
Item_Genres: (table for many-to-many mapping)
Id (int)
objectType (here I have "album" for albums and "video" for videos)
objectId (id from either Albums or Videos table)
genreId (Id of the appropriate genre)
I have a problem with adding a new Genre to my Video.
When I do
videos.Genres.Add(genre);
nHibernate creates a row in Item_Genres table with the right genreId and objectId but with empty objectType. How can I fix that?
Here's my mapping for Video class:
<set name="Genres" table="item_genres" lazy="true" where="objectType = 'video'">
<key>
<column name="objectId" not-null="true"/>
</key>
<many-to-many class="Repositories.Entities.Genre">
<column name="genreId" not-null="true"/>
</many-to-many>
</set>
With it I can request Genres for a Video from DB without any problem, the problem is only with adding new.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来,唯一的情况是使用自定义 sql-insert。
这对我有用。
不幸的是,Fluent NHibernate 不支持这个:(
It seems, that the only case is using a custom sql-insert.
That worked for me.
Unfortunately, Fluent NHibernate doesn't support this :(
像这样的关系确实不应该被映射为多对多。在您的情况下,真正的多对多应该只包含 objectId 和genreId。您应该将此关系映射为双方的一对多,并创建一个名为 ItemGenre 的实际实体来表示您的 item_genres 表。另请注意,这会将您的类映射更改为使用 HasMany 而不是 ManyToMany。这将消除您的定制插入件的需要。
A relationship like that really shouldn't be mapped as a many to many. A true many to many should only contain objectId and genreId in your case. You should map this relationship as a one to many on both sides and create an actual entity called ItemGenre that represents your item_genres table. Also note that this would change your class maps to use HasMany instead of ManyToMany. This would eliminate the need for your custom insert.