简体   繁体   中英

What would be the best way to map this scenario in NHibernate?

I have a table that contains keywords. I have several other tables that can have multiple keywords (pulled from the keywords table). Here is what I have, which works, but it feels like there is a better way to map this. I'm just not sure what it would be (if anything)

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

From the snippet I am not sure what you'd like to achieve... It seems like there is a table '[Keywords]', which has two columns 'Picture_Id' and 'Article_Id'.

So either it is used for a Picture or for Article (other reference is null). It could also mean, that there are multiple same values in the column 'Name'... If I do read it correctly

I guess that more suitable would be many-to-many relation in this case. Single set of unique Keyword.Name . Then there would be pairing table for each relation [ArticleKeyword] [PictureKeyword]

If this is the case, we can do map it like this (see Fluent NHibernate HasManyToMany() Mapping or Fluent NHibernate - HasManyToMany... )

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 
      ;

More reading about many-to-many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM