henkmollema / Dommel

CRUD operations with Dapper made simple.
MIT License
634 stars 100 forks source link

SQLExpression does not use column mapping #271

Closed fernandocristan closed 1 year ago

fernandocristan commented 3 years ago

Hello, I have the following mapping

ToTable("pro_categoria"); Map(x => x.Cod).IsKey().IsIdentity().ToColumn("cod", false); Map(x => x.Descricao).ToColumn("descricao", false); Map(x => x.Ativo).ToColumn("ativo", false);

When performing a search using sqlExpression, columns are not mapped

_conn.From<Categoria>(x => x.Select(x => new { x.Cod, x.Descricao }) .Where(y => y.Cod == 1))

Generated sql = select "Cod", "Descricao" from "pro_categoria" where ("cod" = @p1)

lpicchi commented 2 years ago

As a workaraund you can create a Dto to select only the columns you need, and use this like this (preventing overselection):

public record CategoriaDto()
{
    public string Cod{ get; init; } = default!;
    public string Descricao { get; init; } = default!;
}
    public class CategoriaDtoMap : DommelEntityMap<CategoriaDto>
    {
        public CategoriaDtoMap ()
        {
            ToTable("pro_categoria");
            Map(x => x.Cod).IsKey().IsIdentity().ToColumn("cod", false);
            Map(x => x.Descricao).ToColumn("descricao", false);
        }
    }
  _conn.From<CategoriaDto>(x =>
  x.Select(x => new CategoriaDto())
  .Where(y => y.Cod == 1))

This will generate your SQL without overselecting and with correct mapping

SELECT "pro_categoria"."cod",
       "pro_categoria"."descricao"
FROM   "pro_categoria"
WHERE  ( "pro_categoria"."cod" = $1 ) 
fernandocristan commented 2 years ago

Thanks!