NHibernate使用联接表上的数据映射多对多关系 [英] NHibernate Mapping a Many to Many with Data on Join Table
问题描述
我有一个User
表和一个Address
表.它们通过联接表连接.映射很简单,但是我想在连接表上显示一些数据,这些数据想显示在地址表上.
I have a User
table and an Address
table. They are connected by a join table. The mapping for that is straight forward, but I have some data on the join table that I would like to show up on the Address table.
也许还有更好的方法进行设置,我愿意征求建议.
There may be a better way to set this up also, which I'm open to suggestions for.
这是表结构.
CREATE TABLE [dbo].[User]
(
[Id] INT NOT NULL IDENTITY PRIMARY KEY,
...
)
CREATE TABLE [dbo].[Address]
(
[Id] INT NOT NULL IDENTITY PRIMARY KEY,
...
)
CREATE TABLE [dbo].[AddressType]
(
[Id] INT NOT NULL IDENTITY PRIMARY KEY,
[Name] NVARCHAR( 10 ) NOT NULL, -- Values: 'Shipping', 'Billing'
...
)
CREATE TABLE [dbo].[UserAddress]
(
[UserId] INT NOT NULL FOREIGN KEY REFERENCES [dbo].[User]( [Id] ),
[AddressId] INT NOT NULL FOREIGN KEY REFERENCES [dbo].[Address]( [Id] ),
[AddressTypeId] INT NOT NULL FOREIGN KEY REFERENCES [dbo].[AddressType]( [Id] ),
...
)
我想要的是在用户对象上具有送货地址和账单地址的列表.我将如何映射?我正在使用Fluent NHibernate进行映射.
What I want is to have a list of shipping and billing addresses on the user object. How would I map that? I'm using Fluent NHibernate for mapping.
我最初是从两个联接表BillingAddress
和ShippingAddress
开始的,这两个联接表只是User
和Address
表之间的联接.这可以很好地工作,但是然后有两个表具有完全相同的结构,可以完成相同的操作,而且看起来似乎不正确.
I originally started out with two join tables, BillingAddress
and ShippingAddress
, that were just joins between the User
and Address
tables. This would work fine, but then there are 2 tables with the exact same structure that do the same thing, and it just didn't seem right.
推荐答案
如果您的联接表(例如UserAddress)不仅仅是一对外键,并且其中具有元数据(例如AddressType),则需要映射关联一对多的一对关系,并将关联表示为对象模型中的一个实体.例如:
If your join table (e.g. UserAddress) is more than just a pair of foreign keys and has metadata (e.g. AddressType) in it, you need to map the association as a pair of one-to-many relationships and represent the association as an entity in your object model. For example:
User <has-many> AddressAssociation <references> Address
AddressAssociation将把AddressType作为属性. (基本上,我是将UserAddress重命名为AddressAssociation,以使其听起来更像是域实体.)User to AddressAssociation是User-> AddressAssociation中的一对多对象.引用是AddressAssociation和Address之间的多对一.
AddressAssociation would have the AddressType as a property. (Basically I'm renaming UserAddress to AddressAssociation to make it sound more like a domain entity.) User to AddressAssociation is a one-to-many from User->AddressAssociation. The references is a many-to-one between AddressAssociation and Address.
这篇关于NHibernate使用联接表上的数据映射多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!