实现 Nhibernate 一对多映射

发布于 2024-09-18 09:40:53 字数 883 浏览 3 评论 0原文

我有一个班级学校和另一个班级老师。现在每所学校可以包含 m 名教师,并且一名教师可能属于多个学校。但在教师类中,我不想要一个属性来告诉我教师属于哪些学校。

因此,

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();
    }
}

相同的映射是

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

,教师被定义为,

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

并且定义了预期的简单映射。

现在我希望正确连接这些表,以便当我创建一个 School 对象,然后向其中添加教师并保存它时,我希望将其存储在映射表中,该表的列应为以下 SchoolId、TeacherId。

现在,我如何在映射中使用此表,以便当我保存 School 对象时,我的教师也存储在数据库中,并且在检索 School 对象时,我也检索教师。

任何答案将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

向地狱狂奔 2024-09-25 09:40:53

尝试这个


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

Try this:


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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文