1

Tenho o seguinte cenário:

public class Pedido
    {
        [Key]
        public int Id { get; set; }

        public virtual ICollection<ProdutosPedido> ProdutosPedidos { get; set; }

        public DateTime CreateDate { get; set; }

        public DateTime UpdateDate { get; set; }
    }

public class Produto
    {
        [Key]
        public int Id { get; set; }

        public string Descricao { get; set; }

        public string Valor { get; set; }

        public DateTime DataCadastro { get; set; }

        public virtual ICollection<ProdutosPedido> ProdutosPedidos { get; set; }
    }

 public class ProdutosPedido
    {
        [Key]
        public int ProdutosPedidoId { get; set; }

        public int ProdutoId { get; set; }

        public int PedidoId { get; set; }

        public int Quantidade { get; set; }

        public virtual Produto Produto { get; set; }

        public virtual Pedido Pedido { get; set; }

        public virtual Status Status { get; set; }
    }

Consigo salvar o Pedido com os Produtos sem problema algum, mas quero fazer uma tabela master details para mostrar o Pedido com os seus Produtos.

Segue código da Controller

public ActionResult TodosOsPedidos()
        {
            var pedidos = _db.ProdutosPedidos.Include("Pedido").Include("Produto").Where(x => x.Pedido.Id == 2);
            return View(pedidos);
        }

Código da View:

<table class="table table-condensed table-hover table-striped table-responsive">
    <thead>
        <tr>
            <th style="width: 85px">
                Pedido Nº
            </th>
            <th style="text-align: left">
                Solicitante
            </th>
            <th style="width: 120px">
                Data do Pedido
            </th>
            <th style="width: 120px">
                Atualizado Em
            </th>

            <th style="width: 65px"></th>
        </tr>
    </thead>

    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.PedidoId)
                </td>
                <td style="text-align: left">
                    @Html.DisplayFor(modelItem => item.Pedido.Franqueado.NomeFantasia)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Pedido.CreateDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Pedido.UpdateDate)
                </td>

                <td>
                    <a href="@Url.Action("Edit", "Produtos", new { @id = item.PedidoId })" title="Editar" class="btn btn-xs btn-primary tool">
                        <span class="glyphicon glyphicon-edit"></span>
                    </a>
                    <a href="javascript:void(0)" rel="@item.PedidoId" title="Excluir" class="btn btn-xs btn-danger tool delete-produto">
                        <span class="glyphicon glyphicon-trash"></span>
                    </a>
                </td>
            </tr>
            <tr>
            <td style="width: 100%"  colspan="5">
                <h5>Produtos</h5>
                <table class="table table-condensed table-hover table-striped table-responsive">
                    <thead>
                        <tr>
                            <th>Descrição</th>
                            <th>Quantidade</th>
                            <th>Valor Unitário</th>
                            <th>Valor Total</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>

                            <tr>
                                <td>@Html.DisplayFor(itemModel => item.Produto.Descricao)</td>
                                <td>@Html.DisplayFor(itemModel => item.Quantidade)</td>
                                <td>@Html.DisplayFor(itemModel => item.Produto.Valor)</td>
                                <td>@Html.DisplayFor(itemModel => item.Produto.Descricao)</td>
                                <td>@Html.DisplayFor(itemModel => item.Produto.Descricao)</td>
                                <td></td>
                            </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        }
        </tbody>
</table>

Quero deixar como o exemplo abaixo:

Nº Pedido     Solicitante          Data Criacao   Data Atualizacao
      1            Fornecedor 01        23/05/2014        27/05/2014
----------------------------------------------------------------------------------------------
Descrição     Qntd     Valor Uni     Valor Total         Status       #
Produto 01      02          3,50                7,00        Em Proc    editar

Nº Pedido     Solicitante          Data Criacao   Data Atualizacao
      2            Fornecedor 04       23/05/2014        27/05/2014
----------------------------------------------------------------------------------------------
Descrição     Qntd     Valor Uni     Valor Total         Status       #
Produto 01      02          3,50                7,00        Em Proc    editar
Produto 03      01          3,50                3,50        Em Proc    editar

Porém os pedidos estão se repetindo, todos os pedidos de ID dois são listados com seus produtos, e não apenas 1 Pedido de ID 2 e embaixo os produtos relacionados.

1 Resposta 1

1

Várias coisas pra corrigir:

1. Controller

public ActionResult TodosOsPedidos()
{
    var pedido = _db.Pedidos.Include(p => p.ProdutosPedidos).ToList();
    return View(pedido);
}

Certifique-se que há no cabeçalho a declaração using System.Data.Entity;.

Evite selecionar pela associação.

2. View

Repare que aqui mudo o @model para IEnumerable<Pedido> pra iteração ficar mais intuitiva.

Faltou iterar os pedidos:

<table class="table table-condensed table-hover table-striped table-responsive">
    <thead>
        <tr>
            <th style="width: 85px">
                Pedido Nº
            </th>
            <th style="text-align: left">
                Solicitante
            </th>
            <th style="width: 120px">
                Data do Pedido
            </th>
            <th style="width: 120px">
                Atualizado Em
            </th>

            <th style="width: 65px"></th>
        </tr>
    </thead>

    <tbody>
        @foreach (var item in Model) // Model é IEnumerable<Pedido>
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Id)
                </td>
                <td style="text-align: left">
                    @Html.DisplayFor(modelItem => item.Franqueado.NomeFantasia)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CreateDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.UpdateDate)
                </td>

                <td>
                    <a href="@Url.Action("Edit", "Produtos", new { @id = item.PedidoId })" title="Editar" class="btn btn-xs btn-primary tool">
                        <span class="glyphicon glyphicon-edit"></span>
                    </a>
                    <a href="javascript:void(0)" rel="@item.PedidoId" title="Excluir" class="btn btn-xs btn-danger tool delete-produto">
                        <span class="glyphicon glyphicon-trash"></span>
                    </a>
                </td>
            </tr>
            <tr>
            <td style="width: 100%"  colspan="5">
                <h5>Produtos</h5>
                <table class="table table-condensed table-hover table-striped table-responsive">
                    <thead>
                        <tr>
                            <th>Descrição</th>
                            <th>Quantidade</th>
                            <th>Valor Unitário</th>
                            <th>Valor Total</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var produtoPedido in item.ProdutosPedidos)
                            <tr>
                                <td>@Html.DisplayFor(itemModel => produtoPedido.Produto.Descricao)</td>
                                <td>@Html.DisplayFor(itemModel => produtoPedido.Quantidade)</td>
                                <td>@Html.DisplayFor(itemModel => produtoPedido.Produto.Valor)</td>
                                <td>@Html.DisplayFor(itemModel => produtoPedido.Produto.Descricao)</td>
                                <td>@Html.DisplayFor(itemModel => produtoPedido.Produto.Descricao)</td>
                                <td></td>
                            </tr>
                        }
                    </tbody>
                </table>
            </td>
        </tr>
        }
        </tbody>
</table>
13
  • Na parte "p => p.ProdutosPedidos.Produto" o "ProdutosPedidos" fica vermelho e ao passar o mouse em cima da a seguinte mensagem: "Cannot resolve simbol 'ProdutosPedidos' Code is unreacheble" 6/11/2014 às 20:46
  • @HermesAutran Então tem alguma coisa errada no seu relacionamento em código. Se o ReSharper indica a propriedade em vermelho, significa que ProdutosPedidos não existe no Model Pedido. 6/11/2014 às 20:49
  • As minhas classes estão como acima. =/ 6/11/2014 às 20:52
  • @HermesAutran Colocou using System.Data.Entity no cabeçalho do seu Controller? 6/11/2014 às 20:58
  • Funcionou, o ProdutosPedidos está ok, mas o Produto ficou vermelho. 6/11/2014 às 21:02

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .