代码之家  ›  专栏  ›  技术社区  ›  user48408

与NHibernate的关系

  •  0
  • user48408  · 技术社区  · 15 年前

    我使用两个表,EmployeeGroups和EmployeeGroups,如下所示。我忽略了下面大部分不相关的专栏。我正在努力绘制外键关系图。它是一个一对一的关系,不是EmployeeGroups表中的每个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]
    

    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>
    

    <?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>
    

    1 回复  |  直到 15 年前
        1
  •  0
  •   Stefan Steinegger    15 年前

    这将创建从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