1

我遇到了 linq to entity 查询的问题。

我有 3 个表TransactionSecurityPrices

导航如下: 一笔交易有一种证券,可以有多种价格

我正在尝试做的是使用安全信息和日期小于交易日期的所有价格进行交易。

我写的查询是这样的:

context.Transaction
  .Include("Security.Prices")
  .Where(transaction =>
       transaction.Security.Prices.Any(price => price.Date < transaction.Date))
  .ToList();

这个查询的结果不是我所期望的,对于每个交易,我总是得到证券的所有价格,而不仅仅是日期小于交易日期的价格。

我尝试过的方法是反转查询,试图获取所有交易以获取安全性,过滤安全代码和用户 ID 列表。但即使这次任何过滤器都被忽略了

context.Security
  .Include("Transactions")
  .Where(security => security.Code == code)
  .Where(s => s.Transactions.Any(t => Ids.Contains(t.Id)))
  .ToList();

使用此代码,我可以获得所有用户进行的安全交易,而不仅仅是 Ids 列表中的用户。

我不明白我对这个查询做错了什么?

4

1 回答 1

3

像@Lasse 评论一样,您选择所有价格在交易日期之前的Transaction任何价格。结果集将包括每笔交易的所有价格。您需要Select()在新结果集中过滤它们:

context.Transaction
       .Include("Security.Prices")
       .Where(transaction =>
          transaction.Security.Prices.Any(price => price.Date < transaction.Date))
       .Select(t => new Transaction
       {
           // Only select prices before the given date
           Prices = t.Prices.Where(price => price.Date < transaction.Date),
           OtherProperty = t.OtherProperty,
           // etc...
       })
       .ToList();
于 2013-10-17T07:03:56.723 回答