Return some query columns using LINQ

Asked

Viewed 194 times

1

I have a query that returns me all the columns and I’m using only two columns (id and nome) in my select2, I thought to bring only these columns, I wonder if it is possible to bring in the query only two columns Fornecedor.

I got the following:

Ifornecedorrepository

Task<IEnumerable<Fornecedor>> ObterParaAutocomplete(string text);

Vendordorrepository

public async Task<IEnumerable<Fornecedor>> ObterParaAutocomplete(string text)
{
    return await Db.Fornecedores.AsNoTracking()
        .Where(x => x.Nome.Contains(text))
        .OrderBy(p => p.Nome)
        .ToListAsync();
}

Suppliers

[HttpGet]
public async Task<IActionResult> ObterFornecedor(string text)
{

    if (string.IsNullOrEmpty(text))
    {
        return Json(new
        {
            result = ""
        });
    }
    else
    {
        var dados = _mapper
            .Map<IEnumerable<FornecedorViewModel>>(
                await _fornecedorRepository.ObterParaAutocomplete(text)
            );
        return Json(new
        {
            result = dados
        });
    }

}

Json result

inserir a descrição da imagem aqui

  • No solution worked out?

  • 1

    @Virgilionovic all right! Thank you!

1 answer

1


One can create a ViewModel with two fields (in your field id and nome) and when using ORM Entity Framework do the following:

public class ViewModel 
{
    public int Id { get; set; }
    public string Nome { get; set; }
}

and then in your Interface IFornecedorRepository create a method:

Task<IEnumerable<ViewModel>> ObterParaAutocomplete(string text);

and implement it in the class FornecedorRepository:

public async Task<IEnumerable<ViewModel>> ObterParaAutocomplete(string text)
{
    return await Db.Fornecedores
        .AsNoTracking()
        .Where(x => x.Nome.Contains(text))
        .OrderBy(p => p.Nome)
        .Select(c => new ViewModel { Id = c.Id, Nome = c.Nome })
        .ToListAsync();
}

and this is very good for performance by the amount of information that is really needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.