NHibernate 有一个名为“代码映射”的系统,它使开发人员能够用代码映射他们的数据库(正如其名称所示)。我正在使用 NHibernate 3.3.1。
我已经为两个类做到了这一点:“Gebruiker”和“Lijst”。他们都有一个彼此的列表,因此这是多对多关系的典型示例。
映射如下:
格布鲁伊克
Set(l => l.Lijsten, map =>
{
map.Table("LijstGebruiker");
map.Cascade(Cascade.All);
map.Inverse(true);
map.Key(k => k.Column("Gebruiker"));
}, map => map.ManyToMany(p => p.Column("Lijst")));
李斯特
Set(l => l.Gebruikers, map =>
{
map.Table("LijstGebruiker");
map.Cascade(Cascade.All);
map.Key(k => k.Column("Lijst"));
}, map => map.ManyToMany(p => p.Column("Gebruiker")));
据我所知,这应该会生成表“LijstGebruiker”,其中包含列 Gebruiker 和 Key。
相反:NHibernate 生成一个包含三列的 LijstGebruiker 表,除了两列预期列之外还额外增加了一列:elt。 Elt 还使用外键引用 Lijst。
根据我在互联网上找到的有关此问题的网站,这种情况不应该发生,但事实确实如此。我做错了什么?
最佳答案
显然,这是当列名等于类名时发生的某种奇怪行为。您的代码生成的映射是:
格布鲁伊克
<set name="Lijsten" table="LijstGebruiker" inverse="true" cascade="all">
<key column="Gebruiker" />
<many-to-many class="Lijst" />
</set>
李斯特
<set name="Gebruikers" table="LijstGebruiker" cascade="all">
<key column="Lijst" />
<many-to-many class="Gebruiker" />
</set>
因此,many-to-many
元素中没有列。这可能是 NHibernate 中的一个错误。
如果您将列重命名为 Gebruiker_id
和 Lijst_id
,那么一切正常。
另一种解决方案是使用多列定义方法指定列名称:
格布鲁伊克
Set(l => l.Lijsten, map =>
{
map.Table("LijstGebruiker");
map.Cascade(Cascade.All);
map.Inverse(true);
map.Key(k => k.Column("Gebruiker"));
}, map => map.ManyToMany(p =>
{
p.Columns(x => x.Name("Lijst"));
}));
李斯特
Set(l => l.Gebruikers, map =>
{
map.Table("LijstGebruiker");
map.Cascade(Cascade.All);
map.Key(k => k.Column("Lijst"));
}, map => map.ManyToMany(p =>
{
p.Columns(x => x.Name("Gebruiker"));
}));
代码生成的映射为:
<set name="Lijsten" table="LijstGebruiker" inverse="true" cascade="all">
<key column="Gebruiker" />
<many-to-many class="Lijst">
<column name="Lijst" />
</many-to-many>
</set>
<set name="Gebruikers" table="LijstGebruiker" cascade="all">
<key column="Lijst" />
<many-to-many class="Gebruiker">
<column name="Gebruiker" />
</many-to-many>
</set>
关于c# - NHibernate 中使用代码映射的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12992732/