2009-08-25 94 views
0

我正在使用2個表,Employees和一個名爲EmployeeGroups的表,如下所示。我忽略了下面大部分不相關的列。我正在努力繪製外鍵關係。它是一對一的關係,並不是Employees表中的每個EmployeeId都存在於EmployeeGroups表中。我想知道如何在我的映射文件中設置EmployeeId關係?努力與NHibernate建立關係

員工

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

你不應該只考慮如何映射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創建模式。