How to list products from a single restaurant?

Asked

Viewed 90 times

4

I registered my products in a particular restaurant. Being Restaurant(1) and Products(N), I have several products registered in a restaurant.

How do I list these products for each restaurant?

This is the standard Action:

public ActionResult Cardapio()
    {

        return View(db.Produtos.ToList());
    }

1 answer

5


I would do so:

public ActionResult Cardapio(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var restaurante = db.Restaurantes
                        .Include(r => r.Produtos)
                        .FirstOrDefault(r => r.RestauranteId == id);

    if (restaurante == null)
    {
        return HttpNotFound();
    }

    return View(restaurante.Produtos.ToList());
}

Use:

http://localhost:porta/Restaurantes/Cardapio/1 

Where 1 is the Restaurant Id.

Links:

@Html.ActionLink"Cardápio", "Cardapio", "Restaurantes", new { id = Model.RestauranteId })

Or else:

<a href="@Url.Action("Cardapio", "Restaurantes", new { id = Model.RestauranteId })">Ver Cardápio</a>
  • The logic you used is the one I really needed! But my id up there is null. I need to see what this is.

  • Because I access a list of restaurants, and I click on the details, and I go to his menu. Can you tell me if there’s some kind of mistake along the way?

  • Use as follows: http://localhost:porta/Restaurants/Cardapio/1

  • In detail: @Html.ActionLink("Cardápio", "Cardapio", "Restaurantes", new { id = Model.RestauranteId }). If that’s what I understand.

  • 1

    Wow, true! haha A mistake I had made before at the beginning of the project. Thank you very much, Gypsy! = D

  • @Ciganomorrisonmendez, when we use Include it makes a JOIN in the query that goes to the right bank, but how does it look when using Firstofdefault ? it generates a list of Products with only one Restaurants?

  • 1

    @Exact Gokussjgod. Brings a restaurant with all its products, as advance charge (Join).

Show 2 more comments

Browser other questions tagged

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