Skip to main content
 首页 » 编程设计

c#之如何使用 nhibernate 获取 DTO 成员的集合

2024年01月13日26三少

我需要在 DTO 中填充一个集合属性,但我找不到有关执行此操作的任何信息。

我试着这样做:

ICriteria selectCriteria = Session.CreateCriteria<DataRun>() 
            .SetProjection(Projections.ProjectionList() 
                .Add(Projections.Property("SomeCollection"), "Collection")) 
            .SetResultTransformer(Transformers.AliasToBean<MyDto>()); 

但 MyDto.Collection 始终为空。我做错了吗,这有可能吗?

另外,我最初计划用一个子查询来做这件事,这样我就可以用其他 DTO 填充我的 DTO 集合,但这行不通,因为子查询的结果多于 1 行(应该如此),而 Sqlit 确实如此不是那样的(抛出异常)。在这里做什么是正确的?

请您参考如下方法:

我使用以下语法在我的项目中检索了集合属性:

public IList<ChildCollectionType> GetChildObjectsByParentId(Int32 id) 
{ 
    ISession session = GetSession();//Get NHibernate session routine 
    return session.Load<ParentDTO>(id).ChildCollectionProperty; 
} 

其中 id 是父对象的键。