0
votes

I am very much new to Fluent Nhibernate. I am stuck with the one situation. Please find bellow details about it.

Our table structure is like as

Table Student { Student_Id, Name}
Table School { School_Id, Name}
Table LinkTable { School_Id, Student_Id}

LinkTable contains only id of the Student and School. [Composite Key]

Relation is like 1) One student can be part of 0 or 1 School. 2) One School can contains many students.

Can anyone please let me know how the mapping will be done for each file?

or let mw know what is wrong in following mapping files

Right now, it is giving me error that Student Property is not found on SchoolStudent.

  public Student()
{
    Id(x => x.Id);
    Map(x => x.Name);
    HasOne(x => x.SchoolStudent).PropertyRef(r => r.Student);
}

public School()
{
    Id(x => x.Id);
    Map(x => x.Name);
    HasMany(x => x.SchoolStudent).KeyColumn("School_Id").Inverse().Cascade.AllDeleteOrphan();
}

public SchoolStudent()
{
    CompositeId().KeyReference(x => x.School, "School_Id")
            .KeyReference(x => x.Student, "Student_Id");
}

Thanks, Mahesh

2

2 Answers

1
votes

I would re-write it to something like this:

Student.cs

public class Student 
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<School> Schools { get; set; }

    public Student() 
    {
        Schools = new List<School>();
    }
}

School.cs

public class School 
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Student> Students { get; set; }

    public School() 
    {
        Students = new List<Student>();
    }
}

StudentMap.cs

public class StudentMap : ClassMap<Student>
{
    public Student()
    {
        Id(x => x.Id    , "Student_Id");
        Map(x => x.Name , "Name");

        HasManyToMany(x => x.Schools).Table("LinkTable")
                                     .ParentKeyColumn("Student_Id")
                                     .ChildKeyColumn("School_Id");
    }
}

SchoolMap.cs

public class SchoolMap: ClassMap<School>
{
    public School()
    {
        Id(x => x.Id    , "School_Id");
        Map(x => x.Name , "Name");

        HasManyToMany(x => x.Students).Table("LinkTable")
                                      .ParentKeyColumn("School_Id")
                                      .ChildKeyColumn("Student_Id");
    }
}
1
votes

If a student can only be associated with 0 or 1 schools, then you might consider dropping the LinkTable and the SchoolStudent class and just add School_Id to the Student table and a reference to School in the Student class.

Then your mappings are like:

public Student()
{
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.School);
}

public School()
{
    Id(x => x.Id);
    Map(x => x.Name);
    HasMany(x => x.Student).Inverse().Cascade.AllDeleteOrphan();
}