如何使用EF Core中的其他字段执行sql select查询?

时间:2017-12-13 22:48:34

标签: c# entity-framework

我有下一个型号:

[Table("clients")]
    public class ClientDto : BaseModelDto
    {
        [Required]
        [StringLength(70, MinimumLength = 3)]
        [Column("fio")]
        public string FIO { get; set; }

        [StringLength(100, MinimumLength = 3)]
        [Column("address")]
        public string Address { get; set; }

        [Phone]
        [Column("phone")]
        public string Phone { get; set; }        

        public List<RealizationDto> Realizations { get; set; }
    }

我需要执行sql查询并获得结果:

public async Task<ClientDto> GetTheMostValuableCustomer()
    {
      var result = await Context.Clients.FromSql<ClientDto>(@"
        select clients.id, clients.fio, clients.address, clients.phone, sum(goods.price*realizations.quantity) max_cost
            from clients
            inner join realizations on clients.id=realizations.client_id
            inner join goods on realizations.good_id=goods.id
            group by clients.id
            order by max_cost desc
        limit 1;
    ").ToListAsync();

  return result.FirstOrDefault();
}

此问题适用于PostgreSql,但不适用于服务器级别,因为ClientDto模型和选择字段不同。 (max_cost不存在于ClientDto模型中)。但是当我执行查询时,我得到一个错误,即字段&#34; max_cost&#34;不存在。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要更改:

sum(goods.price*realizations.quantity) max_cost

为:

sum(goods.price*realizations.quantity) AS max_cost