NHibernate 3.2通过代码进行多对多映射

时间:2012-03-05 20:15:40

标签: nhibernate mapping many-to-many nhibernate-3 mapping-by-code

我正在尝试学习NHibernate 3.2 built-in mapping by code api FluentNHibernate,也不是xml)。你能帮助我映射这些实体之间的多对多关系吗?

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

我的主要关键策略是:

Id( 
    t => t.Id, 
    t => { 
        t.Generator(Generators.HighLow, g => g.Params(new { max_low = 100 })); 
        t.Column(typeof(TEntity).Name + "Id"); 
    });

我试试这个:

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

但它不起作用。

2 个答案:

答案 0 :(得分:30)

// 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")));

答案 1 :(得分:1)

我认为你需要设置密钥告诉nhibernate它需要检查多对多表上的哪个列,如下所示:

// TagMap
bag.Key(k => k.Column("TagId"));

// PostMap
bag.Key(k => k.Column("PostId"));