nhibernate映射,多对一

时间:2012-07-18 08:36:19

标签: nhibernate

我有实体房子,除了其他属性列表的图像。 每个图像将作为单个动作上传,使用js裁剪技术逐个上传。

更新 所以一个房子可以有很多图像。

public House
{
  public Guid Id {get; set;}
  ....
  List<Image> Images {get; set;}
}

public class Images 
{
  public House House {get; set;}
  public string Path {get;set;}
  public string Name {get;set;}
  public string Description {get;set;}    
}

我的数据库表如下:

House 
 Id
 Name, ...
 On this side I don't have relation to the Image table

Image table
 Id
 HouseId
 Path
 Name
 Description

这种方法可以吗? 如何使用nhibernate orm映射这些对象?

由于

2 个答案:

答案 0 :(得分:0)

House.hbm.xml:

<bag name="Images" cascade="all-delete-orphan" inverse="true">
    <key column="HouseId" />
    <one-to-many class="Image" />
</bag>

Image.hbm.xml:

<id type="int" column="Id">
    <generator ... />
</id>

<many-to-one name="House" column="HouseId" cascade="none" />

由于您在图像表中有一个主键,而域对象中没有 Id 属性,因此id-mapping应该没有name-attribute。

答案 1 :(得分:0)

声明您的实体,然后在映射文件中将图像HouseIdHouse类的实体关联起来。你应该在db中有外键。正如xml已经在这里回答,我会添加流畅的nhibernate方式。

public class House
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    ....
}

public class Image 
{
    public virtual int Id { get; set; }
    public virtual House HouseEntity { get; set; }
    ....
}

public class HouseMap : ClassMap<House>
{
    public HouseMap()
    {
        Table("House");

        Id(x => x.Id).GeneratedBy.Identity();            
        Map(x => x.Name);
        .....
    }
}

public class ImageMap : ClassMap<Image>
{
    public ImageMap()
    {
        Table("Image");

        Id(x => x.Id).GeneratedBy.Identity();
        References(x => x.House);
        //References(x => x.House, "foreignKeyName"); There is also way to reference with specifying foreign key field
        Map(x => x.Name);
        ....
    }
}