简体   繁体   中英

Implementing Nhibernate one to many mapping

I have a class School and another class Teachers. now every school can contain m Teachers and one Teacher may be part of more than one school. But in the Teachers class I dont want a property that tells me which Schools a teacher is part of.

Thus,

public class School
{
public virtual int Id {get;set;}
public virtual string Name {get;set;}
public virtual IList<Teacher> Teachers {get;set;}
    public School()
    {
    Teachers=new List();
    }
}

And the mapping for the same is

public class SchoolMap:ClassMap<School>
{
    public SchoolMap()
    {
    Id(x=>x.Id);
    Map(x=>x.Name);
    HasMany(x=>x.Teachers);
    }
}

and Teacher is defined as

public class Teacher
{
public virtual int Id {get;set;}
public virtual int Name {get;set;}
}

and the expected simple mapping is defined.

Now I wish to join these tables right so that when I create a School object and then add Teachers to it and save it I want it to be stored in a mapping table the columns of which should be the following SchoolId,TeacherId.

Now how do i use this table in my mapping so that when I save the School object my teachers are also stored in the db and on retrieving the School object I retrieve the Teachers too.

Any answer would be appreciated.

试试这个

HasMany(x => x.Teachers).Inverse().Cascade.All();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM