如何获取对父级和子级应用过滤器的子级集合
我正在使用 nHibernate 从 Sql Server 数据库检索订单集合(及其订单行)。
这是我的 ShipmentOrder 类:
public class ShipmentOrder
{
private ICollection<ShipmentDetail> _ShipmentsDetails;
public virtual ReadOnlyCollection<ShipmentDetail> ShipmentsDetails
{
get { return (new List<ShipmentDetail>(_ShipmentsDetails).AsReadOnly()); }
}
}
nHibernate 返回一个 IList,其中加载了所有详细信息 (ShipmentsDetails)(因为我渴望加载它们)。
现在,我想过滤 ShipmentOrder 和 ShipmentDetail 的集合并返回 ShipmentDetail 的集合。
我尝试过这样的事情:
IList<ShipmentOrder> Results;
// Fetch orders using nHibernate
Results = FetchOrders();
var shipmentLines = Results
.Where(x => x.Company == "XXX" && x.OrderNumber == "111")
.SelectMany(x => x.ShipmentsDetails)
.Where(s => s.RowNumber == 1 && s.RowSeq == 0)
.ToList();
但我意识到我获得了同一行的多个结果。
我已经像这样转换了 lamda 表达式:
var shipmentLines = Results
.Where(x => x.Company == "XXX" && x.OrderNumber == "111")
.SelectMany(x => x.ShipmentsDetails)
.Where(s => s.RowNumber == 1 && s.RowSeq == 0)
.Distinct()
.ToList();
并且它工作正常。 我想知道是否有更好的方法可以在没有 distinct 的情况下达到相同的结果。
更新:
我在这里使用 SelectMany,因为这是我发现将过滤器应用于子项(ShipmentsDetails)的唯一方法。
I am using nHibernate to retrieve a collection of orders (and its order lines) from a Sql Server database.
This is my ShipmentOrder class:
public class ShipmentOrder
{
private ICollection<ShipmentDetail> _ShipmentsDetails;
public virtual ReadOnlyCollection<ShipmentDetail> ShipmentsDetails
{
get { return (new List<ShipmentDetail>(_ShipmentsDetails).AsReadOnly()); }
}
}
nHibernate returns a IList with all the details (ShipmentsDetails) loaded (since I Eager load them).
Now, I would like to filter my collection of ShipmentOrder and ShipmentDetail and get back a collection of ShipmentDetail.
I've tried something like this:
IList<ShipmentOrder> Results;
// Fetch orders using nHibernate
Results = FetchOrders();
var shipmentLines = Results
.Where(x => x.Company == "XXX" && x.OrderNumber == "111")
.SelectMany(x => x.ShipmentsDetails)
.Where(s => s.RowNumber == 1 && s.RowSeq == 0)
.ToList();
But I've realized that I obtain multiple results of the same line.
I've converted the lamda expression like this:
var shipmentLines = Results
.Where(x => x.Company == "XXX" && x.OrderNumber == "111")
.SelectMany(x => x.ShipmentsDetails)
.Where(s => s.RowNumber == 1 && s.RowSeq == 0)
.Distinct()
.ToList();
and it works fine.
I was wondering if there's a better way to achieve the same result without the distinct.
UPDATE:
I am using SelectMany here cause this is the only way I've found to apply filters to children (ShipmentsDetails).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来像 Linq2Objects,因此 IList 结果包含重复的记录,可能您急切地提取到深层,不幸的是导致重复的根实体。在查询中使用distinctrootentity-resulttransformer
this looks like Linq2Objects, therefor the IList Results contains duplicate records, probably you do eager fetching to levels deep which unfortunatly results in duplicate root entities. use distinctrootentity-resulttransformer in the query