首页 > 解决方案 > 将 SQL 查询转换为实体框架的问题

问题描述

有 Product 和 Price 表,价格表包含 Product 表的外键 Price.ProductId。Price 表包含有关每个产品的价格信息,这些价格可能会根据 StartDate 进行更改,换句话说,用户可以为任何产品指定确切的 StartDate 的新价格。它如何在实体框架的帮助下实现?Product 实体模型有一个包含来自 Price 表的实体的集合,但不适合提取这么多 Price 实体,因为 Product 必须仅与最终查询中的实际价格相关联。

有 2 个模型映射表 -

public partial class Product
{
    public long Id { get; set; }
    public string ProductName { get; set; }
    public virtual ICollection<Price> Prices { get; set; }
}

public partial class Price
{
    public long Id { get; set; }
    public long ProductId { get; set; }
    public DateTime StartDate { get; set; }

    public virtual Product Product { get; set; }
}

无法提取完整集合 Product.Price,只有一个实际价格必须与 Product 关联。看起来下面的 SQL 查询可以提取数据,但是如何在 EF 的帮助下完成呢?

select public.price., public.product. from public.product  
inner join public.price on public.price."ProductId" = public.product."Id"
where public.price."Id" in 
(
    select max(public.price."Id") from public.price
    where public.price."StartDate" <= current_date 
    group by  public.price."ProductId" 
)

标签: c#postgresqlentity-framework-6asp.net-core-5.0

解决方案


大概,它必须是这样的——

var productsWithPrice = await db.Product
                        .Select(p => new 
                        { 
                            Product = p,
                            Price = p.Prices.Where(x => x.StartDate <= DateTime.UtcNow).OrderBy(x => x.StartDate).LastOrDefault()
                        })
                        .ToListAsync();

推荐阅读