Search code examples
c#asp.net-mvclinqdatareader

Having an issue with "DataReader already open"


I've searched on SO and didn't find any answer to the problem I'm having.

I made a linq to get all data from two tables and one ajax call to get new data and fill my dropdownlist as the other dropdownlist changes.

Here's what I have so far:

Controller

public ActionResult Index(int? page)
{
    vEntities db = new vEntities();

    var estados = (from e in db.estado
                   select e);

    var localidades = (from l in db.localidade
                       select l);

    ViewData["estados"] = new SelectList(estados, "cod", "descricao");
    ViewData["localidades"] = new SelectList(localidades, "id", "descricao");

    return View();
}

public ActionResult GetLocalidades(string codEstado)
{
    vEntities db = new vEntities();

    var info = (from l in db.localidade
                where l.cod_estado == codEstado
                select l);

    return Json(info);
}

View

<%= Html.DropDownList("estados", ViewData["estados"] as SelectList, String.Empty)%>
<%= Html.DropDownList("localidade", ViewData["localidades"] as SelectList, String.Empty)%>

<script type="text/javascript">
    $(document).ready(function () {
        $("#estados").change(function () {
            var ddlLocalidade = $("#localidade")[0];
            ddlLocalidade.length = 0;
            var cod = $(this).val();

            $.post(
                "/Home/GetLocalidades",
                { codEstado: cod },
                function (data) {
                    var option;
                    $.each(data, function () {
                        option = new Option(this.descricao, this.id);
                        ddlLocalidade.options.add(option);
                    });
                }
                );

        });
    });
</script>

And when I change the first dropdown, which activates the JS function, I'm getting this error right after the method "Getocalidades" returns the Json:

There is already an open DataReader associated with this Connection which must be closed first

I guess I'm having some trouble formatting the code :) sorry for that.

I can't see any problem with the connection, can anyone tell me what's wrong, please ?

Thanks in advance


Solution

  • This is just a guess. But what happens if you change these lines

    var estados = (from e in db.estado select e);
    
    var localidades = (from l in db.localidade select l);
    
    var info = (from l in db.localidade where l.cod_estado == codEstado select l);
    

    to

    var estados = (from e in db.estado select e).ToList();
    
    var localidades = (from l in db.localidade select l).ToList();
    
    var info = (from l in db.localidade where l.cod_estado == codEstado select l).ToList();