实体框架忽略任何子句
本文关键字:任何 子句 框架 实体 | 更新日期: 2023-09-27 18:35:39
我遇到了linq到实体查询的问题。
我有3张桌子:Transaction
,Security
和Prices
。
导航如下:一笔交易有一种证券,可以有很多价格
我正在尝试做的是获取包含安全信息和所有价格的交易,该日期小于交易日期。
我写的查询是这样的:
context.Transaction
.Include("Security.Prices")
.Where(transaction =>
transaction.Security.Prices.Any(price => price.Date < transaction.Date))
.ToList();
此查询的结果不是我所期望的,对于每笔交易,我总是得到证券的所有价格,而不仅仅是日期小于交易日期的价格。
我尝试过的 Anthor 事情是反转查询,试图获取证券的所有交易,过滤安全代码和用户 ID 列表。 但即使这次,任何过滤器也被忽略
了context.Security
.Include("Transactions")
.Where(security => security.Code == code)
.Where(s => s.Transactions.Any(t => Ids.Contains(t.Id)))
.ToList();
使用此代码,我获得了所有用户(而不仅仅是 Ids 列表中的用户)进行的安全性的所有事务。
我不明白我在这个查询中做错了什么?
与@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();