我正在使用2个表,Employees和一个名为EmployeeGroups的表,如下所示。我遗漏了下面大部分不相关的专栏。我正在努力映射外键关系。它是一对一的关系,而Employees表中的每个EmployeeId都不会存在于EmployeeGroups表中。我想知道如何在下面的映射文件中设置EmployeeId关系?
员工
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[ForeName] [nvarchar](20) COLLATE Latin1_General_CI_AI NOT NULL,
[SurName] [nvarchar](20) COLLATE Latin1_General_CI_AI NOT NULL,
CONSTRAINT [PK_Employees_1] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
EmployeeGroups
CREATE TABLE [dbo].[EmployeeGroups](
[GroupId] [int] NULL,
[EmployeeId] [int] NOT NULL,
[Active] [int] NULL,
CONSTRAINT [PK_EmployeeGroups] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
USE [DemoDEV]
GO
ALTER TABLE [dbo].[EmployeeGroups] WITH CHECK ADD CONSTRAINT
[FK_EmployeeGroups_Employees] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[Employees] ([EmployeeId])
到目前为止我的员工映射文件
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="AdaptiveMaintenance.Core.Domain.Employee, AdaptiveMaintenance.Core" table="Employees" lazy="false">
<id name="ID" column="EmployeeId">
<generator class="assigned" />
</id>
<property name="Forename" column="ForeName" not-null="true"/>
<property name="Surname" column="SurName" not-null="true"/>
</class>
</hibernate-mapping>
到目前为止,我的EmployeeGroups映射文件看起来像这样
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="AdaptiveMaintenance.Core.Domain.EmployeeGroup, AdaptiveMaintenance.Core" table="EmployeeGroups" lazy="false">
<id name="ID" column="EmployeeId">
<generator class="foreign" />
</id>
<property name="Active" column="Active" />
</class>
答案 0 :(得分:0)
你不应该只考虑如何映射db模型,你应该总是考虑类模型:它应该是什么样的?
这将创建从EmployeeGroup到Employee的引用。
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="AdaptiveMaintenance.Core.Domain.EmployeeGroup, AdaptiveMaintenance.Core" table="EmployeeGroups" lazy="false">
<id name="ID" column="GroupId">
<generator class="assigned" />
</id>
<property name="Active" column="Active" />
<many-to-one name="Employee" class="Employee" column="EmployeeId"/>
</class>
当你有一对一的关系尝试耦合主键时,为什么会有GroupId?我把它作为一个独立的主键。
顺便说一句,如果要创建新的数据库模型,则首先设计类更容易,之后映射它们并使用SchemaExport
创建模式。