添加Nhibernate预测

时间:2013-09-10 07:29:20

标签: nhibernate icriteria nhibernate-projections

Employee: BaseEntity课程

public virtual BaseEntity Department {get;set;}
public virtual BaseEntity Position {get;set;}

BaseEntity类:

public virtual long Id {get;set;}
public virtual long Name {get;set;}

如何映射我的实体和/创建像这样的选择

SELECT  DepartmentTable.nvarchar1 as Department, PositionTable.nvarchar1 as Position,    COUNT(*) as N      
FROM AllUserData EmployeeTable 
    left outer join AllUserData PositionTable on EmployeeTable.int2=PositionTable.tp_ID 
    left outer join AllUserData DepartmentTable on  EmployeeTable.int3=DepartmentTable.tp_ID         
 WHERE  EmployeeTable.tp_ListId = @p0 and PositionTable.tp_ListId = @p2 and DepartmentTable.tp_ListId = @p1
GROUP BY DepartmentTable.nvarchar1, PositionTable.nvarchar1;

我试过这样:

var criteria = session.CreateCriteria<Entities.Employee>();
criteria.CreateAlias("Position", "PositionTable", JoinType.LeftOuterJoin);
criteria.Add(Restrictions.Or(Restrictions.Eq("PositionTable.ListId", Program.PositionListGuid), Restrictions.IsNull("PositionTable.Id")));

criteria.CreateAlias("Department", "DepartmentTable", JoinType.LeftOuterJoin);
criteria.Add(Restrictions.Or(Restrictions.Eq("DepartmentTable.ListId", Program.DepartmentListGuid), Restrictions.IsNull("DepartmentTable.Id")));

criteria.Add(Restrictions.Eq("ListId", Program.EmployeeListGuid));
var projectionList = Projections.ProjectionList();
projectionList.Add(Projections.RowCount());
projectionList.Add(Projections.GroupProperty("Department"), "AliasedId");
criteria.SetProjection(projectionList);
criteria.SetResultTransformer(Transformers.AliasToBean(typeof(BaseEntity)));
var list = criteria.List<BaseEntity>();
// "More than one row with the given identifier was found" exception raised here

我很困惑,我应该以某种方式为Projections.GroupProperty使用连接表别名,重写我的映射/实体以仅使用原始类型(字符串,整数)或任何其他方法吗?

1 个答案:

答案 0 :(得分:0)

想通了:

int Number添加到BaseEntitystring DepartmentNamestring PositionName添加到Employee。现在我可以使用Projections将按结果分组的Sql映射到此属性:

var pl = Projections.ProjectionList()
.Add(Projections.RowCount(), GetEntityProperty(typeof (BaseEntity), "Number"))
.Add(Projections.GroupProperty("DepartmentTable.Title"), "PositionName")
.Add(Projections.GroupProperty("PositionTable.Title"), "DepartmentName");                                 
ICriteria criteria = session.CreateCriteria<Employee>()
.CreateAlias("Position", "PositionTable", JoinType.LeftOuterJoin)
.Add(Restrictions.Eq("PositionTable.ListId", Program.PositionListGuid))
.CreateAlias("Department", "DepartmentTable", JoinType.LeftOuterJoin)
.Add(Restrictions.Eq("DepartmentTable.ListId",Program.DepartmentListGuid))
.Add(Restrictions.Eq("ListId", Program.EmployeeListGuid))                                               
.SetProjection(pl)
.SetResultTransformer(Transformers.AliasToBean<BaseEntity>());

var list = criteria.List<BaseListEntity>().ToList();