简体   繁体   English

在NHibernate中映射此方案的最佳方法是什么?

[英]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'. 从代码片段中,我不确定您要实现什么...似乎有一个表[[Keywords]',其中有两列'Picture_Id'和'Article_Id'。

So either it is used for a Picture or for Article (other reference is null). 因此,它可用于PictureArticle (其他参考为空)。 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. 我猜在这种情况下,更合适的是many-to-many关系。 Single set of unique Keyword.Name . 一组唯一的Keyword.Name Then there would be pairing table for each relation [ArticleKeyword] [PictureKeyword] 然后每个关系都有一个配对表[ArticleKeyword] [PictureKeyword]

If this is the case, we can do map it like this (see Fluent NHibernate HasManyToMany() Mapping or Fluent NHibernate - HasManyToMany... ) 如果是这种情况,我们可以像这样进行映射(请参见Fluent NHibernate HasManyToMany()映射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 有关多对多的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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