流利的Nhibernate HasManyToMany继承

时间:2013-12-23 16:23:40

标签: nhibernate fluent-nhibernate fluent-nhibernate-mapping

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public List<Literature> LiteratureCources { get; set; }
    public List<Drawing> DrawingCources { get; set; }
    public List<Internet> InternetCources { get; set; }
}

public class cource
{
    public int CourceId { get; set; }
    public string CourceName { get; set; }
}

public class Literature : cource
{
    public LiteratureType LiteratureType { get; set; }
}

public class Drawing : cource
{
    public DrawingType DrawingType { get; set; }
}

public class Internet : cource
{
    public InternetType InternetType { get; set; }
}
public enum LiteratureType
{
    L1, L2, L3
}

public enum DrawingType
{
    D1, D2, D3
}
public enum InternetType
{
    I1, I2, I3
}

Tables
------

Student
-------
StudentId
StudentName

Cource
------
CourceId (PK)
CourceName

InternetCource
--------------
InternetCourceId (FK)
InternetType

DrawingCource
-------------
DrawingCourceId (FK)
DrawingType

LiteratureCource
----------------
LiteratureCourceId (FK)
LiteratureType

StudentCource  (mybridge table)
-------------
StudentId 
CourceId

public class LiteratureCourceMap:ClassMap<Literature>
{
    public LiteratureCourceMap()
    {
        Table("Cource");
        ID(a=>a.CourceId,"CourceId");
        Map(a=>a.CourceName,"CourceName");

        Join("LiteratureCource",a=>{
            a.KeyColumn("CourceId");
        });
    }
}

绘图和互联网的相同映射

public class StudentMap:ClassMap<Student>
{
    public StudentMap()
    {
        Table("Student");
        ID(a=>a.StudentId,"StudentId");
        Map(a=>a.StudentName,"StudentName");

        HasManyToMany(a=>a.InternetCources).Table("StudentCource").
            ParentKeyColumn("StudentId").
            ChildKeColumn("CourceId").
            Cascade.All();

         HasManyToMany(a=>a.DrawingCources).Table("StudentCource").
            ParentKeyColumn("StudentId").
            ChildKeColumn("CourceId").
            Cascade.All();

         HasManyToMany(a=>a.LiteratureCources).Table("StudentCource").
            ParentKeyColumn("StudentId").
            ChildKeColumn("CourceId").
            Cascade.All();
    }
}

现在当插入数据时,如果工作正常,数据会正确存储在相应的表中 但是,如果尝试获取数据出错的话

让我们说如果插入2个文献资源和1个互联网资源。 如果从表中获取数据我有3个文献记录(2个记录填充1个空或空)和3个互联网记录(1个填充和2个空)。请帮我正确映射

1 个答案:

答案 0 :(得分:0)

看来,NHibernate总是从Cource表中获取,因为有主键。您应该尝试子类映射。见这个例子:

public class CourceMap : ClassMap<Cource>
{
  public CourceMap()
  {
    Id(x => x.CouerceId);
    Map(x => x.CourceName);
  }
}

public class DrawingMap : SubclassMap<Cource>
{
  public DrawingMap()
  {
    Map(x => x.DrawingType);
  }
}

请参阅此内容以进一步阅读:https://github.com/jagregory/fluent-nhibernate/wiki/Fluent-mapping