NHibernate 3.2 many to many mapping by code
Asked Answered
M

2

11

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.

Melmela answered 5/3, 2012 at 20:15 Comment(0)
L
31
// 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")));
Lanie answered 5/3, 2012 at 23:6 Comment(1)
Can you add some explanation about not using any cascading?Rabiah
W
1

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"));
Wichman answered 5/3, 2012 at 20:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.