在NHibernate中映射这个场景的最好方法是什么?

本文关键字:方法 是什么 NHibernate 映射 | 更新日期: 2023-09-27 18:17:43

我有一个包含关键字的表。我有几个其他的表,可以有多个关键字(从关键字表拉)。这是我所拥有的,它是有效的,但感觉有更好的方法来绘制它。我只是不确定它会是什么(如果有的话)

public class Keyword
{
    public virtual int Id {get; protected set;}
    public virtual string Name {get; set;}
}
public class KeywordMap : ClassMap<Keyword>
{
    public KeywordMap()
    {
        Id(x => x.Id).Not.Nullable().GeneratedBy.Identity();
        Map(x => x.Name).Not.Nullable.Length(100);
    }
}
public class Article
{
    public virtual int Id {get; protected set;}
    //... other properties omitted
    public virtual IList<Keyword> Keywords {get; set;}
}
public class ArticleMap : ClassMap<Article>
{
    public ArticleMap()
    {
        Id(x => x.Id).Not.Nullable().GeneratedBy.Identity();
        HasMany(x => x.Keywords).Inverse().Cascade.Delete();
    }
}
public class Picture
{
    public virtual int Id {get; protected set;}
    //... other properties omitted
    public virtual IList<Keyword> Keywords {get; set;}
}
public class PictureMap : ClassMap<Picture>
{
    public PictureMap()
    {
        Id(x => x.Id).Not.Nullable().GeneratedBy.Identity();
        HasMany(x => x.Keywords).Inverse().Cascade.Delete();
    }
}

在NHibernate中映射这个场景的最好方法是什么?

从片段我不确定你想要实现什么…似乎有一个表'[关键词]',其中有两列'Picture_Id'和'Article_Id'。

因此它要么用于Picture,要么用于Article(其他引用为null)。它也可能意味着,在列'Name'中有多个相同的值…如果我没看错的话

我想在这种情况下many-to-many关系更合适。单套独特的Keyword.Name。然后每个关系对应一个配对表[ArticleKeyword] [PictureKeyword]

如果是这种情况,我们可以这样做映射(参见Fluent NHibernate hasmanymany () Mapping或Fluent NHibernate - hasmanymany…)

public ArticleMap()
{
    Id(x => x.Id).Not.Nullable().GeneratedBy.Identity();
    HasManyToMany<Keyword>(x => x.Keyword)
      .Table("ArticleKeyword")
      .ParentKeyColumn("Article_Id") // lot of mapping could be omited 
      .ChildKeyColumn("Keyword_Id")  // thanks to conventions 
      ;

更多关于多对多的阅读

  • http://nhibernate.info/doc/nh/en/index.html collections-bidirectional
  • http://ayende.com/blog/4043/nhibernate-mapping-list