【发布时间】:2022-07-13 04:13:36
【问题描述】:
我的数据库结构如下:
public class Ticket
{
public int Id { get; set; }
public List<History> Histories { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class History
{
public int Id { get; set; }
public Employee Employee { get; set; }
public DateTime Timestamp { get; set; }
}
用户提供要过滤的属性名称和查询字符串。我想到的是我需要允许用户通过Tickets 中的计算属性查询Tickets,例如
public Employee LatestEmployee
{
get => History.MaxBy(x=>x.Timestamp).Employee;
}
有人建议我严格保留实体模型以反映数据库结构并使用单独的类来表示实体的可查询属性:
public class TicketSummary
{
public int TicketId {get;set;}
public Employee LatestEmployee {get;set;}
}
public IQueryable<TicketSummary> BuildSummaryQuery()
{
return _context.Tickets.Select(t => new TicketSummary
{
TicketId = t.Id,
LatestEmployee = t.History.MaxBy(x=>x.Timestamp).Employee
});
}
然后拨打BuildSummaryQuery().Where(x=>x.LatestEmployee.Name == "Batman")。但是,我发现MaxBy() 无法转换为 MySQL 数据库上的有效查询。我不断收到The LINQ expression could not be translated。如何计算出类似的有效查询?
【问题讨论】:
标签: c# mysql dynamic-linq ef-core-6.0