问题
I'm trying to learn NHibernate 3.2 built-in mapping by code api
(NOT FluentNHibernate, nor xml). Can you help me to map a many-to-many relationship between these entities please?
public class Post {
public virtual Id { get; set; }
public IList<Tag> Tags { get; set; }
}
public class Tag {
public virtual Id { get; set; }
public IList<Post> Posts { get; set; }
}
My primary key strategy is:
Id(
t => t.Id,
t => {
t.Generator(Generators.HighLow, g => g.Params(new { max_low = 100 }));
t.Column(typeof(TEntity).Name + "Id");
});
and I try this:
// TagMap : ClassMapping<Tag>
Bag(t => t.Posts, bag => {
bag.Inverse(true);
bag.Table("TagsPosts");
bag.Cascade(Cascade.DeleteOrphans);
}, t => t.ManyToMany(c => {
c.Column("PostId");
c.Lazy(LazyRelation.Proxy);
}));
// PostMap : ClassMapping<Post>
Bag(t => t.Tags, bag => {
bag.Table("TagsPosts");
bag.Cascade(Cascade.DeleteOrphans);
}, t => t.ManyToMany(c => {
c.Column("TagId");
c.Lazy(LazyRelation.Proxy);
}));
but it doesn't work.
回答1:
// Post Map
Bag(x => x.Tags, collectionMapping =>
{
collectionMapping.Table("TagPosts");
collectionMapping.Cascade(Cascade.None);
collectionMapping.Key(k => k.Column("PostID"));
},
map => map.ManyToMany(p => p.Column("TagID")));
// Tag Map
Bag(x => x.Posts, collectionMapping =>
{
collectionMapping.Table("TagPosts");
collectionMapping.Cascade(Cascade.None);
collectionMapping.Key(k => k.Column("TagID"));
},
map => map.ManyToMany(p => p.Column("PostID")));
回答2:
I think you need to set the key to tell nhibernate which column on the many-to-many table it needs to check, something like this:
// TagMap
bag.Key(k => k.Column("TagId"));
// PostMap
bag.Key(k => k.Column("PostId"));
来源:https://stackoverflow.com/questions/9573326/nhibernate-3-2-many-to-many-mapping-by-code