c# - 将 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"
)
解决方案
大概,它必须是这样的——
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();
推荐阅读
- apache-storm - __execute-count 值与 Metrics Reporting API v2 收集的值之间的差异
- python - 在python中为文件添加水印
- python - 变量没有draw属性?
- jquery - Select2:是否可以在初始化后以编程方式更新“tags:true”属性值?
- flutter - Sliding_Up_Panel 中的 SlideDirection 颤动
- c# - 带有特殊字符的邮件 URI - 无法解析主机名
- python - 当我尝试减去时,我得到一个错误的响应
- reactjs - 如何在不更改所有按钮颜色的情况下更改地图功能内的按钮颜色?
- javascript - 如何从经度和纬度中获得1英里的纬度三角洲和经度三角洲?
- css - CSS mix-blend-mode:跨浏览器和监视器的差异不一致