nHibernate对未映射实体计数

| 使用nHibernate 2。 在我们的系统中,我们有一个表,用于存储可能指向系统中其他任何表的记录以及一些其他字段。例如
class PointerTable
{
    public int ID;
    public string ObjectName;
    public int RecordID;
    ... additional fields
}
ObjectName和RecordID字段指向系统中另一个表的名称,以及该记录指向的该表中记录的ID。该表与系统中的其他表之间没有关系。 当我从系统中的其他表中检索记录时,我需要能够加入该表,因为我需要确定某个表在PointerTable中是否有指向该表的记录。即获取该记录的PointerTable中的记录数。 我已经尝试在HQL中执行此操作:
select a.ID, e.Field1, a.Field2, a.Field3,
            count(select * 
             from PointerTable p
             where p.ObjectName = \"Table1\"
               and p.RecordID = a.ID)
from Table1 a 
where a.ParentTable.ID = :ID
我还研究了将映射表放入系统中所有实体的XML配置文件中。因此,我可以在其他每个实体中都有一个PointerTable记录集合。虽然我不确定这是否可行。我找不到如何将映射设置为映射到2个字段而不是主键上。 就像是:
<bag name=\"PointerRecords\" table=\"PointerTable\" lazy=\"true\" inverse=\"true\">      
     <key>
         <column name=\"ThisEntityID\" />
         <column name=\"ObjectName\" />  ?? Hard coded
    </key>
    <one-to-many class=\"PointerTable\" not-found=\"ignore\"/>      
</bag>
这有可能吗? 基本上,我想做的只是以下SQL查询。但理想情况下,我们希望通过HQL或映射进行此操作。 的SQL
select a.ID, e.Field1, a.Field2, a.Field3, Count(d.ID)
from Table1 a 
inner join Table2 e on a.ParentID=e.ID
left outer join PointerTable d on d.ObjectName = \'Table1\' and d.RecordID = a.ID
where c.ID = @ID
group by a.ID, e.Field1, a.Field2, a.Field3
    
已邀请:
        这里的想法是用where子句映射这个集合 使用fluentmapping:
public SomeEntityMap(){
    Table(\"SomeTable\");

    HasMany(x => x.PointerRecords)
        .Table(\"PointerTable\")
        .KeyColumn(\"ThisEntityID\")
        .Where(\"ObjectName = \'SomeTable\'\")
}
开始编辑 使用xml映射
<bag name=\"PointerRecords\" table=\"PointerTable\" lazy=\"true\" inverse=\"true\" where =\"ObjectName = \'SomeTable\'\">
    <key column=\"ThisEntityID\"/>
    <one-to-many class=\"PointerTable\" not-found=\"ignore\"/>
</bag>
结束编辑 和查询像
object[] results = session.CreateCriteria<SomeEntity>()
    .Add(Restrictions.Eq(\"Id\", id))
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property(\"Field1\"))
        ...
        .Add(Projections.Count(\"PointerRecords\")));
    .List()
要么
var entities = session.CreateCriteria<SomeEntity>()
    .Add(Restrictions.Eq(\"Id\", id)
    .SetFetchMode(\"PointerRecords\", NHibernate.FetchMode.Eager)
    .List<SomeEntity>();

entities[0].PointerRecords.Count
    

要回复问题请先登录注册