[英]Entity Framework Core - Calling a Where linq method doesn't have relations
I'm a newcomer to EF core, and I have a problem when I try to do the following.我是 EF 核心的新手,当我尝试执行以下操作时遇到问题。 I have some business logic that filters coffees based on the price:
我有一些根据价格过滤咖啡的业务逻辑:
if(request.MoreThen != null)
{
query = query.Where(c =>
c.Prices
.OrderByDescending(p => p.CreatedAt)
.First()
.Price
>= request.MoreThen);
}
And it works all and well.它运作良好。 However, when I try to extract this functionality into a private method, I get that the
Prices
relation is null.但是,当我尝试将此功能提取到私有方法中时,我发现
Prices
关系为空。
Now, I have several places I need to referance the latest price, here's the second if:现在,我有几个地方需要参考最新价格,这是第二个如果:
if(request.MoreThen != null)
{
query = query.Where(c =>
c.Prices
.OrderByDescending(p => p.CreatedAt)
.First()
.Price
>= request.MoreThen);
}
I find this not DRY at all, so I wanted to extract the fetching of the price into a private method like so:我发现这根本不是 DRY,所以我想将价格的提取提取到一个私有方法中,如下所示:
private decimal GetPrice(Coffee model)
{
return model.Prices
.OrderByDescending(p => p.CreatedAt)
.First()
.Price
}
However, now when I substitute the query:但是,现在当我替换查询时:
query = query.Where(c => GetPrice(c) <= request.LessThen)
I get a weird error, and in the debugger every field is present except for the Included ones.我收到一个奇怪的错误,在调试器中,除了包含的字段外,每个字段都存在。 ( Do note that I called the
.Include
) method. (请注意,我调用了
.Include
)方法。
The full code sample is included in my open source Project on Github完整的代码示例包含在我在 Github 上的开源项目中
EDIT: I'm using Postgres as the Database engine, and code first approach编辑:我使用 Postgres 作为数据库引擎,代码优先方法
So my question is, why are the .Prices
null even though I've included them at the start of the method?所以我的问题是,为什么
.Prices
空,即使我已经在方法的开头包含了它们?
I couldn't figure out how to operate on the Coffee
class itself, however you can create an extension method on IQueryable<Coffee>
.我无法弄清楚如何对
Coffee
类本身进行操作,但是您可以在IQueryable<Coffee>
上创建一个扩展方法。
For example:例如:
public static class Extensions
{
public static IQueryable<Coffee> GetPriceMoreThen(this IQueryable<Coffee> query, decimal moreThen)
{
return query.Where(c =>
c.Prices
.OrderByDescending(p => p.CreatedAt)
.First()
.Price >= moreThen);
}
}
which then you can call as such然后你可以这样调用
query = query.GetPriceMoreThen(request.MoreThen);
Disclaimer: I'm making some assumptions on your model here免责声明:我在这里对您的模型进行了一些假设
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.