【问题标题】:What would be the best way to map this scenario in NHibernate?在 NHibernate 中映射这种情况的最佳方法是什么?
【发布时间】:2013-06-10 20:18:49
【问题描述】:

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

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

【问题讨论】:

    标签: c# nhibernate nhibernate-mapping


    【解决方案1】:

    从 sn-p 我不确定您想要实现什么...似乎有一个表“[Keywords]”,其中有两列“Picture_Id”和“Article_Id”。

    所以它要么用于Picture,要么用于Article(其他引用为空)。这也可能意味着“名称”列中有多个相同的值......如果我没看错

    我想在这种情况下更合适的是many-to-many 关系。单组唯一Keyword.Name。然后每个关系都有配对表[ArticleKeyword][PictureKeyword]

    如果是这种情况,我们可以像这样映射它(参见Fluent NHibernate HasManyToMany() MappingFluent 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 
          ;
    

    更多关于多对多的阅读

    【讨论】:

    • “所以它要么用于图片,要么用于文章(其他参考为空)。这也可能意味着“名称”列中有多个相同的值......如果我这样做正确阅读”这是正确的,但实际上有 5 个表可以(可选)有一个关键字,所以按照我的方式映射它,我最终为每条记录有 4 个空列,这对我来说似乎效率低下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多