nHibernate Mapping By Code - One to Many and Many to One

Mapping by code是nHibernate3.2新增的功能,网络上及官方doc相关的介绍都很少。下面是如何使用mapping by code的方式配置一对多和多对一关联的例子。

 

关于如何配置nhibernate使用mapping by code,参考nHibernate Mapping By Code - Introduction

 

1. 实体类

public class Employee
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string IdentityNumber { get; set; }
    public virtual Department Department { get; set; }
}

public class Department
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Employee> Employees { get; set; }
}

 

2. 数据库表(基于MS SQL Server 2012)

CREATE TABLE [dbo].[Department](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED ([Id] ASC)

CREATE TABLE [dbo].[Employee](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [IdentityNumber] [varchar](50) NOT NULL,
    [DepartmentId] [int] NOT NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([Id] ASC)

ALTER TABLE [dbo].[Employee] ADD CONSTRAINT [FK_Employee_DepartmentId] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Department] ([Id])

 

3.  映射类

public class DepartmentMapping : ClassMapping<Department>
{
    public DepartmentMapping()
    {
        Table("Department");
        Id(department => department.Id, map => map.Generator(Generators.Identity));
        Property(department => department.Name);
        Bag(department => department.Employees, map => map.Key(k => k.Column("DepartmentId")), rel=> rel.OneToMany());
    }
}

public class EmployeeMapping : ClassMapping<Employee>
{
    public EmployeeMapping()
    {
        Table("Employee");
        Id(employee => employee.Id, map => map.Generator(Generators.Identity));
        Property(employee => employee.Name);
        Property(employee => employee.IdentityNumber);
        ManyToOne(employee => employee.Department, map => map.Column("DepartmentId"));
    }
}

 


示例代码基于nHibernate3.3.1

转载请注明出处

转载于:https://www.cnblogs.com/iamzhenyu/archive/2012/07/01/nHIbernate_map_by_code_one_to_many.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值