Select with filter on entity being generated duplicate

0

I have a droplist that lists the states, which when a state is selected it filters the cities for that state. It turns out that when I select cities it comes duplicated.

For example, I have states in select that are São Paulo, Minas Gerais e Espirito Santo , when I select Minas Gerais for example, it fires an ajax to consume cities that exist for that state. If I select Minas Gerais, it would have to appear only, Belo Horizonte, Betim, Contagem , it happens that Belo Horizonte, Betim, Contagem, Belo Horizonte, Betim, Contagem appears in duplicate form.

By analyzing the query return that the entity assembles, something like this

SELECT 

    [Extent1].[Id] AS [Id], 
    [Extent1].[Nome] AS [Nome]
    FROM [dbo].[Cidade] AS [Extent1]
    WHERE ([Extent1].[UfId] = 'MG') OR (([Extent1].[UfId] IS NULL) AND ('MG' IS NULL)) 

That really brings back the duplicate data.

The problem is that I do not understand why the entity is generating the query this way.

Follow my entity's function

  [WebMethod]
  [ScriptMethod(UseHttpGet = true)]
  public JsonResult buscarCidades()
  {
     string estado = Request.QueryString["estado"];
     var cidades = db.Cidade.Where(e => e.UfId == estado).Select(c => new { c.Id, c.Nome });

    return Json(cidades, JsonRequestBehavior.AllowGet);
  }

Thank you in advance

    
asked by anonymous 11.04.2018 / 18:17

1 answer

1

When duplicate registration happens, always try to use distinct in the query you are searching for. It usually works.

SELECT DISTINCT

[Extent1].[Id] AS [Id], 
[Extent1].[Nome] AS [Nome]
FROM [dbo].[Cidade] AS [Extent1]
WHERE ([Extent1].[UfId] = 'MG') OR (([Extent1].[UfId] IS NULL) AND ('MG' IS NULL))
    
11.04.2018 / 18:28