Fluent NHibernate only generating one extra column for multiple HasMany relationships
I have a thesaurus application built on NHibernate. The data model is very straight-forward:
public class Word
{
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual IList<Word> Synonyms { get; set; }
public virtual IList<Word> Antonyms { get; set; }
}
So each word has a list of synonyms and a list of antonyms. I thought the mapping would be straight-forward as well:
public class WordMapping : ClassMap<Word>
{
public WordMapping()
{
Id(x => x.Id);
Map(x => x.Text);
HasMany(x => x.Synonyms).Cascade.All开发者_运维问答DeleteOrphan();
HasMany(x => x.Antonyms).Cascade.AllDeleteOrphan();
}
}
When I look at the table generated in MS SQL Server 2008, I only see one key column for the two HasMany relations:
Id int
Text nvarchar(255)
Word_id int
I think this is causing some weird things to happen when I insert data. When I get the lists after doing some insertions, both Synonyms
and Antonyms
contain the same Words
, but the Words
are just seemingly-arbitrary subsets of what should be in the two lists.
Do I have the problem pegged right? If so, how can I fix it?
I was way off base. I assumed FNH was generating a separate table for the HasMany relationships (it wasn't). Proper code found here: Fluent NHibernate Self Referencing Many To Many
Specific to my problem, I created two separate tables:
-- Synonyms table --
WordId int
SynonymId int
-- Antonyms table --
WordId int
AntonymId int
Then in my mapping class:
public class WordMapping : ClassMap<Word>
{
public WordMapping()
{
Id(x => x.Id);
Map(x => x.Text);
HasManyToMany(x => x.Synonyms).ParentKeyColumn("WordId")
.ChildKeyColumn("SynonymId")
.Table("Synonyms");
HasManyToMany(x => x.Antonyms).ParentKeyColumn("WordId")
.ChildKeyColumn("AntonymId")
.Table("Antonyms");
}
}
That fixes all the issues.
精彩评论