Select with filter in Entity being generated duplicate

Asked

Viewed 37 times

0

I have a droplist that lists the states, that when a state is selected it filters the cities related to that state. It turns out that when I select cities comes duplicate.

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 triggers an ajax to consume the cities that exist for that state. If I selected Minas Gerais, I would have to appear only, Belo Horizonte, Betim, Contagem , happens to appear Belo Horizonte, Betim, Contagem, Belo Horizonte, Betim, Contagem duplicate.

Analyzing the return of the query that 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 duplicated data.

The problem is that I don’t understand why Entity is generating the query this way.

Follows my Entity 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);
  }

Thanks in advance

1 answer

1

When duplicate registration happens, always try to use the distinct in the query you do the search in. 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))
  • 1

    Thanks for the reply, I’ll put a distinct in Entity and see if it gives

Browser other questions tagged

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