我不熟悉NHibernate投影。我试图使用它,所以我可以返回一个List<>而是一个IList<>。到目前为止,我没有太多运气投入DTO。我有以下查询和域对象。所以开始我只是想获得一个给定EmployeeID的订单列表。我循环遍历结果列表并将其添加到List中,因为我希望能够序列化此列表。谁能告诉我我与投影有多远?我搜索并发现了一些与我自己不相似的例子。基本上......我只是想创建一个DTO列表。
谢谢!
public List<EmployeeOrder> GetEmployessOrdersDTO(int empid)
{
var emporders = new List<EmployeeOrder>();
ICriteria criteriaSelect = NHibernateSessionManager.Instance.GetSession().CreateCriteria(typeof (Orders))
.CreateCriteria("Employees")
.Add(Expression.Eq("EmployeeID", empid));
criteriaSelect.SetProjection(
Projections.ProjectionList()
.Add(Projections.Property("Products"), "OrderedProducts"));
criteriaSelect.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(EmployeeOrder)));
criteriaSelect.List<EmployeeOrder>();
foreach (var order in emporders)
{
emporders.Add(order);
}
return emporders;
}
订单:
public class Orders
{
public virtual int OrderID { get; private set;}
public virtual string CustomerID { get; set; }
public virtual DateTime OrderDate { get; set; }
public virtual DateTime RequiredDate { get; set; }
public virtual DateTime ShippedDate { get; set; }
public virtual Employees Employee { get; set; }
public virtual IList<Products> Products { get; private set; }
}
雇员:
public class Employees
{
public virtual int EmployeeID { get; private set;}
public virtual string LastName { get; set;}
public virtual string FirstName { get; set;}
public virtual string City { get; set; }
public virtual DateTime HireDate { get; set; }
public virtual string Title { get; set; }
public virtual IList<Orders> Orders { get; private set; }
}
EmployeeOrderDTO:
public class EmployeeOrder
{
public virtual string EmployeeName { get; set; }
public virtual string EmployeeTitle { get; set; }
public virtual DateTime RequiredDate { get; set; }
public virtual List<Products> OrderedProducts { get; set; }
}
答案 0 :(得分:4)
在nHibernate 2.1中,.List()方法实际上已经返回了一个List类型,所以你可以只强制转换:
var list = (List<EmployeeOrder>)criteriaSelect.List<EmployeeOrder>();
但是,如果您希望将来安全并且不依赖于基于当前nHibernate实现的假设,我会编写一个接受ICriteria的扩展方法:
public static List<T> ToList<T>(this ICriteria criteria)
{
return criteria.List<T>().ToList();
}
答案 1 :(得分:2)
更改
criteriaSelect.List<EmployeeOrder>();
到
List<EmployeeOrder> employeeOrders = criteriaSelect.List<EmployeeOrder>() as List<EmployeeOrder>;