映射多对多关系的问题(按代码映射)

时间:2011-07-10 23:37:50

标签: nhibernate nhibernate-mapping

我正在使用新的NHibernate 3.2映射代码(不流利的nhibernate),我在映射多对多关系时遇到了一些问题。

我想映射这些实体

 public class Article
    {
        public virtual Guid Id { set; get; }
        public virtual string Content { set; get; }
        public virtual string Title { set; get; }
        public virtual IList<Tag> Tags { set; get; }
    }
 public class Tag
    {
        public virtual Guid Id { set; get; }
        public virtual string Name { set; get; }
        public virtual IList<Article> Articles { set; get; }
    }

    public class ArticleTag
    {
        public virtual Article Article { set; get; }
        public virtual Tag Tag { set; get; }
    }

我的映射看起来是

  public class TagMapping : ClassMapping<Tag>
        {
            public TagMapping()
            {
                Id<Guid>(x => x.Id);
                Property<string>(x => x.Name);
                Bag<Article>(x => x.Articles, x => x.Inverse(true), x => x.ManyToMany(z =>
                {
                    z.Column("Article");
                    z.Lazy(LazyRelation.Proxy);
                }));
            }
        }
        public class ArticleTagMapping : ClassMapping<ArticleTag>
        {
            public ArticleTagMapping()
            {
                ManyToOne<Article>(x => x.Article, x => { });
                ManyToOne<Tag>(x => x.Tag, x => { });
            }
        }
       public class ArticleMapping : ClassMapping<Article>
        {
            public ArticleMapping()
            {
                Id<Guid>(x => x.Id, x => x.Generator(Generators.Guid));
                Property<string>(x => x.Content, x => x.Length(4002));
                Property<string>(x => x.Title);
                Bag<Tag>(x => x.Tags, x =>{ }, x => x.ManyToMany(z =>
                {
                    z.Column("Tag");
                    z.Lazy(LazyRelation.Proxy);
                }));
            }
        }

唯一的问题是,当我使用这个模式在数据库中生成表时,我有两个额外的表。我必须更改以禁用生成这两个表(文章和标签)? enter image description here

1 个答案:

答案 0 :(得分:1)

你真的需要这个吗?:

 public class ArticleTagMapping : ClassMapping<ArticleTag>
        {
            public ArticleTagMapping()
            {
                ManyToOne<Article>(x => x.Article, x => { });
                ManyToOne<Tag>(x => x.Tag, x => { });
            }
        }