Modify queries made by the scaffolding first database

0

I tell you a bit about my problem.

By my boss's requirements I had to make an application using the first database technique and then use scaffolding (which I do not like). I was used to doing linq queries and calling them in my controller, now I want to modify a view where it brings me a list with all the records of a table, but I want to discriminate some, in which file or class I can modify it?.

Reviewing the code, it is not clear to me if my driver brings the query or the information from the database. if so, how can I add a filter as well as a where ?

Here my controller that I am using:

    public ActionResult Index()
    {
        var usuarios = db.Usuarios.Include(u => u.UsuariosRol);
        return View(usuarios.ToList());
    }
    
asked by Luna 17.07.2017 в 17:47
source

2 answers

1

I recommend you determine the data to be displayed from the controller's action method through some filter mechanism, such as the Where extension method. The idea is that the action method invokes the view by transferring only the data that you want to display.

public ActionResult Index()
{
    var usuarios = db.Usuarios.Include(u => u.UsuariosRol).Where(u => u.Estatus == true);
    return View(usuarios.ToList());
}
    
answered by 17.07.2017 / 18:35
source
0

I was able to solve the problem myself, the fastest way to filter the information that the query generated by the scaffolding brought me directly to the view, with razor evaluating the model already loaded with info.

I would like to clarify, I do not recommend that you do so since, although the information is filtered properly, you will always be pulling all the records which is not optimal:).

@foreach (var item in Model) {
if (item.Estatus == true)
{
<tr>
    <td>
        @Contador
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Nombre)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Contrasena)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Descripcion)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.UsuariosRol.Nombre)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.IdUsuario }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.IdUsuario })
    </td>
</tr>
    Contador = Contador + 1;
}
}

documenting me a bit more, I leave the correct way to filter the information through the controller, it is done by a delegate, just call your data context, then the table and call the where method together with the field that you will evaluate. the include below is for when it is required to do an inner join with another table (fill combobox for example)

 public ActionResult Index()
    {
        var usuarios = db.Usuarios
            .Where(u=> u.Estatus.Equals(true))
            .Include(u => u.UsuariosRol);
        return View(usuarios.ToList());
    }
    
answered by 17.07.2017 в 18:09