我试图将此 sql 表达为 EF Core 8 查询
SELECT DISTINCT
PRICE, UPDAT, f.ID AS fundid, f.coreserie
FROM
performance.FUND f
INNER JOIN
performance.ULTIMO_FUND_NAV_LIMITED u ON u.ID = f.ID
WHERE
f.id = 51
AND (f.startdate IS NULL OR u.updat >= f.startdate)
AND (f.endDate IS NULL OR u.updat <= f.endDate)
ORDER BY
u.UPDAT;
我已经映射了
Fund
和 UltimoFundNavLimited
实体。
这就是我目前所拥有的。但这不适用于数据库。
我收到警告
函数不可转换为 SQL,并且不得在数据库上下文中调用
var lst = await _context.Funds
.Where(f => f.Id == fundId)
.Include(x=>x.UltimoFundNavLimited)
.SelectMany(f => f.UltimoFundNavLimited, (f, u) => new { Fund = f, Ultimo = u })
.Where(x => x.Ultimo.Update >= x.Fund.StartDate
&& x.Ultimo.Update <= x.Fund.EndDate)
.ToListAsync();
这些是模型类:
public class Fund
{
public int Id { get; set; }
public string Name { get; set; }
public int CoreSerieId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public List<UltimoFundNavLimited> UltimoFundNavLimited { get; set; }
}
public class UltimoFundNavLimited
{
public int FundId { get; set; }
public DateTime Update { get; set; }
public decimal Price { get; set; }
public decimal Value { get; set; }
}
对于使用多个表的查询,最好使用查询语法:
var query =
from f in _context.Funds
from u in f.UltimoFundNavLimited
where f.Id == fundId &&
(f.StartDate == null || u.Update >= f.StartDate) &&
(f.EndDate == null || u.Update <= f.EndDate)
orderby u.Update
select new
{
u.Price,
u.Update,
fundid = f.Id,
f.CoreSerieId
};
var lst = query
.Distinct()
.ToList();