Error while searching with Entityframework

Asked

Viewed 81 times

1

I’m having a problem with a request, in the controller when I query the products table appears the following message when debugging, I click on an icon and does not return any data, but the table has data and I put to return all:

Location : The Function Evaluation requires all threads to run

SQL : The Function Evaluation requires all threads to run

View

<script type="text/javascript" src="~/Scripts/jquery-3.3.1.js"></script>
<script type="text/javascript">
    function carregarProdutos(id) {

        $list = $("#produto-target");
        console.log(id);
        $.ajax({
            url: "GetProdutos",
            type: "POST",
            data: { id: id },
            dataType: 'json',
            traditional: true,
            success: function (result) {
                $list.empty();
                $.each(result, function (item) {
                    $list.append('<option value="' + item["produtoid"] + '"> ' + item["nome"] + ' </option>');
                });
            },
            error: function () {
                alert("Algo deu errado.");
            }
        });
    }      
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Compra</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FornecedorId, "Fornecedor", htmlAttributes: new { @class = "control-label col-md" })
            <div class="col-md-10">
                @Html.DropDownList("FornecedorId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.FornecedorId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CartegoriaId, "Categoria", htmlAttributes: new { @class = "control-label col-md" })
            <div class="col-md-10">
                @Html.DropDownList("CategoriaId", null, htmlAttributes: new { @class = "form-control", @onchange = "carregarProdutos(this.value)" })
                @Html.ValidationMessageFor(model => model.CartegoriaId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProdutoId, "Produto", htmlAttributes: new { @class = "control-label col-md" })
            <div class="col-md-10">
                @Html.DropDownList("ProdutoId", null, htmlAttributes: new { @class = "form-control", @id = "produto-target" })
                @Html.ValidationMessageFor(model => model.ProdutoId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Valor, htmlAttributes: new { @class = "control-label col-md" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Valor, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Valor, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Quantidade, htmlAttributes: new { @class = "control-label col-md" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Quantidade, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Quantidade, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Cadastrar Compra" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Voltar", "Index")
</div>

Controller

[HttpPost]
[Route("GetProdutos/id")]
public async Task<ActionResult> GetProdutos(int? id)
{
    var listaProdutos = new List<Produto>();


    if(id == null)
    {
        return Json("Não há produtos");
    }

    listaProdutos = await GetProdutosPorIdCategoriaAsync((int)id);

    return Json(listaProdutos);
}

public async Task<List<Produto>> GetProdutosPorIdCategoriaAsync(int idCategoria)
{
    return await db.Produtos.ToListAsync();
}

2 answers

2

See if this solves:

[HttpPost]
[Route("GetProdutos/id")]
public async Task<ActionResult> GetProdutos(int? id)
{
    var listaProdutos = new List<Produto>();

    var task = Task.Run(() => Json("Não há produtos"));
    if(id == null)
    {
        return await task;
    }

    listaProdutos = await GetProdutosPorIdCategoriaAsync((int)id);
    task = Task.Run(() => Json(listaProdutos));

    return await task;
}

I didn’t get to test the code, if necessary I’ll come back here to edit.

  • It didn’t happen. List has no Tolist and no Tolistasync

  • @Diegoaquino, in debug the error occurs in this line: Return await db.Produtos.Tolistasync();?

  • Yes, exactly.

  • @Diegoaquino I edited the answer, see if it works.

  • 1

    George, I was able to resolve by changing this configuration property -> db.Configuration.Proxycreationenabled = false. I appreciate your help.

  • 1

    @Diegoaquino, you can put another answer here with the solution you found and accept it as for your question. It can be useful for more people. :)

Show 1 more comment

1


I was able to solve by placing this property -> db.Configuration.Proxycreationenabled = false. The code was Like this:

        [HttpGet]
        public async Task<ActionResult> GetProdutos(int? id)
        {
            db.Configuration.ProxyCreationEnabled = false;

            if(id == null)
            {
                return HttpNotFound("Erro com a categoria.");
            }

            var lista = await GetProdutosPorIdCategoriaAsync((int)id);

            return Json(lista, JsonRequestBehavior.AllowGet);
        }

Browser other questions tagged

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