Query to the C# mvc database

Asked

Viewed 4,362 times

3

How is the syntax or how do I transform a query with multiple joins to a search in my application in c#Asp.net mvc? Example: I have a form with the following controller

        public ActionResult Pesquisa(int id = 0)
    {

        var resultado = context.Graduacoes.Include(e => e.Cursos).Where(e => e.Id == id).ToList();

        ViewBag.Graduacoes = new SelectList(db.Graduacoes, "Id", "Nome");

      return View(resultado);
    }

I need the user to select the rank from the list and click 'Search' return me the name and other information of the individuals who have that rank. In the bank I would do so:

select e.Id, c.Nome from Curso c
inner join Escolaridade e 
on e.Id = NívelId

Models

    public class Graduacao
{
    public int Id { get; set; }

    [Required(ErrorMessage = "O Nome é obrigatório.")]
    [StringLength(50, ErrorMessage = "O nome pode ter no máximo 50 caracteres.")]
    public string Nome { get; set; }

    [Range(0, 20, ErrorMessage="O Nível deve ser um número positivo até 20.")]
    public int Nível { get; set; }

    public virtual ICollection<Curso> Cursos { get; set; }
}

    public class Curso
{
    public int Id { get; set; }

    [Required(ErrorMessage = "O Nome é obrigatório.")]
    [StringLength(50, ErrorMessage = "O Nome pode ter no máximo 50 caracteres.")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "A Instituição é obrigatória.")]
    [StringLength(50, ErrorMessage = "A Instituição pode ter no máximo 50 caracteres.")]
    public string Instituição { get; set; }

    [Required(ErrorMessage = "O Nível do curso é obrigatório.")]
    public int? NívelId { get; set; }
    public virtual Escolaridade Nível { get; set; }

View

@model IEnumerable<Competências.Models.Graduacao>

<title>Pesquisa por Graduação </title>

<div> 
     @using (Html.BeginForm())
     {

    <div class="form-group">

        @Html.DropDownList("Graduacoes")

    </div>

    <button type="submit" id="pesquisar" class="btn btn-primary btn-xs">Buscar</button>
     }
</div>
<div>
<table>

    @{
        if (Model != null)
        {
            foreach (var item in Model)
            {
        <tr>
        <th>Nome </th>

    </tr>
                <tr>
                      <td width="30%">@item.Nome</td> 

           </tr>

            }
        }
    }
</table>
    </div>

I wanted here, when choosing a graduation for example "High School" return me the name of all courses registered with high school. I want to return more things, but summarized for this.

1 answer

2

Warning: this answer was developed from what the author of the question mentioned. Any redundancy or odd detail that may appear is from the various editions that this response had.

I’m guessing you have a mapping like this in your application:

public class Graduacao
{
    [Key]
    public int GraduacaoId { get; set; }

    public virtual ICollection<Curso> Cursos { get; set; }
}

public class Curso
{
    [Key]
    public int CursoId { get; set; }
    public int PerfilId { get; set; }
    public int GraduacaoId { get; set; }

    public virtual Perfil Perfil { get; set; }
    public virtual Graduacao Graduacao { get; set; }
}

public class Perfil
{
    [Key]
    public int PerfilId { get; set; }

    public virtual ICollection<Curso> Cursos { get; set; }
}

So, a select basic would look like this:

public ActionResult Index(int id) 
{
    var resultados = context.Graduacoes
                        .Include(g => g.Cursos)
                        .Where(g => g.GraduacaoId == id).ToList();

    ViewBag.Graduacao = new SelectList(db.Graduacao, "Id", "Nome");

    return View(resultados);
}

Perfil should be loaded by lazy load, which is automatically done by the Entity Framework.


EDIT

Change your Controller for:

public ActionResult Index() 
{
    ViewBag.Graduacao = new SelectList(db.Graduacao, "Id", "Nome");

    return View();
}

[HttpPost]
public ActionResult Pesquisa(int id) 
{
    var resultados = context.Graduacoes
                        .Include(g => g.Cursos)
                        .Where(g => g.GraduacaoId == id).ToList();

    ViewBag.Graduacao = new SelectList(db.Graduacao, "Id", "Nome");

    return View("Index", resultados);
}

View:

<div> 
     @using (Html.BeginForm("Pesquisa", "Graduacoes"))
     {

         <div class="form-group">
             @Html.DropDownList("Graduacoes")

         </div>

         <button type="submit" id="pesquisar" class="btn btn-primary btn-xs">Buscar</button>
     }
</div>
  • What is the correct way to do this view? My model is just as you described it and I made the query. But when I click on "Search" returns the error: The model item passed into the Dictionary is of type 'System.Collections.Generic.List1[Competências.Models.Graduacao]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Skills.Models.Course]'.

  • Well, the mistake is clear. The first line of View has to be @model IEnumberable<Competencias.Models.Graduacao>, and not @model IEnumberable<Competencias.Models.Curso>.

  • Sorry, that was not the mistake. is: "There is no Viewdata item of type 'Ienumerable<Selectlistitem>' that has the key 'Graduate'." pointing to my dropdownlist which is "@Html.Dropdownlist("Graduation")

  • The mistake is because you have a statement of @Html.DropDownList that is not being loaded correctly. Try removing the statement using comments @* *@ and repeat the test.

  • It is loading correctly. I see the options I want in the list, choose one and when searching gives this error. Commenting on the line as you asked I do not see the dropdownlist, only the search button. And when you click it, nothing happens.

  • Got it. It’s actually a screen that lists courses based on graduation. You can undo the comment in Dropdown. I’ll improve the response.

  • Ta, was using two actions with the same name and in your example you put the two in one. ok, when I search now gives no error, it just returns nothing. I have to initialize the id no? (int id = 0)

  • That’s right. The problem of initializing Id is that it can give ambiguity problem in the prototype of Action. Better treat Id within the method.

  • but if I don’t initialize the id or wheel. Gives "The Parameters Dictionary contains a null entry for Parameter 'id'" I left initialized already. There is some problem in the consultation. I’m not getting any feedback

  • Then it’s just debug.

  • I will edit my question by passing model, controller and view. Can you take a look? I’ve tried everything and can’t return anything with the search

  • @Pfvictor Okay, I’m waiting for you.

  • Ready Gypsy, edited!

  • I was using a view only. In the case that you passed will be the right Index?

  • @Pfvictor Remains a View only, but using two Actions in Controller to logic.

Show 10 more comments

Browser other questions tagged

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