如何在nHibernate中更正映射此域对象

时间:2013-11-21 09:59:23

标签: c# nhibernate orm

在数据库中我有文章和集。集包含一些文章。 以下是数据库中集合的示例结构:

 SetID | ArticleID | Count  
 #1    |  #2       |   1 
 #1    |  #3       |   2 

使用id设置:#1包含2个ID为#2和#3的文章。 我的域对象看起来像这样:

class Set
{
  ... 
  ICollection<SetComponent> Components {get; set;}
}

class SetComponent 
{ 
   Article Article {get;set;}
   int Amount {get;set;}
}

如何使用nHibernate将其映射到数据库?

1 个答案:

答案 0 :(得分:0)

选项1:

class SetComponent 
{ 
    public virtual Set ContainingSet { get; set; }
    public virtual Article Article { get; set; }
    public virtual int Amount { get; set; }
}

public SetComponentMap()
{ 
    CompositeId()
        .KeyReference(x => x.ContainingSet, "SetID")
        .KeyReference(x => x.Article, "ArticleID");

    Map(x => x.Amount, "Count");
}

long setId = 5;
var components = session.Query<SetComponent>().Where(c => c.ContainingSet.Id == setId);
var set = new Set(setId, components);

选项2:

class Set
{ 
    public virtual long Id { get; private set; }
    public virtual IList<SetComponent> Components { get; private set; }
}
class SetComponent 
{ 
    public virtual Article Article { get; set; }
    public virtual int Amount { get; set; }
}

public SetMap()
{ 
    Table("Sets");
    Id(x => x.Id, "SetId");

    // not pretty but has to be there to only return 1 row per id
    Where("ArticleID = (SELECT MIN(s.ArticleID) FROM Sets s WHERE s.SetId == SetId)");

    HasMany(x => x.Components)
        .Table("Sets")
        .KeyColumn("SetId")
        .Component(c =>
        {
            c.Reference(x => x.Article, "ArticleID");
            c.Map(x => x.Amount, "Count");
        });
}