How to list data with Inner Join with mvc 5, c#, Dapper, and sql server?

Asked

Viewed 866 times

1

I’m having the following difficulties:

1 - Data display from a select with Inner Join. The fields of the other tables do not appear all that are in select, and the ones that appear, have the value zero (0).

2 - Write the data to the database.Even applying "[Bind(Exclude="Id")]", the "Id" field continues to appear when creating new.
The following will post the codes and some images for better understanding.

MODEL

 public class VendaModel
{

    [Display(Name = "ID")]
    public int id_vd { get; set; }
     [Display(Name = "PRODUTO")]
    public int id_pd { get; set; }
     [Display(Name = "CLIENTE")]
    public int id_cl { get; set; }
    [Display(Name = "DATA")]
    public DateTime data_vd { get; set; }
    [Display(Name = "QTD")]
    [Required(ErrorMessage = "A quantidade é obrigatória!")]
    public int qtd_vd { get; set; }

}

GRAPHIC DIAGRAM inserir a descrição da imagem aqui REPOSITORY

 public class VendaRepositorio
{
    private const string BuscaTodosSQL = "select id_vd,nome_pd,preco_pd,qtd_vd,nome_cl,telef_cl from VENDA inner join CLIENTE on VENDA.id_cl=CLIENTE.id_cl inner join PRODUTO on VENDA.id_pd=PRODUTO.id_pd";
    private const string GravaVendaSQL = "INSERT INTO VENDA (id_pd,id_cl,data_vd,qtd_vd) VALUES(@idpd,@idcl,@data,@qtd)";

    public SqlConnection con;

    //para a conexão com a bd
    private void Conexao()
    {
        string strConexao = ConfigurationManager.ConnectionStrings["LojaMVC5Dapper.Properties.Settings.SqlConexao"].ConnectionString.ToString();
        con = new SqlConnection(strConexao);
    }

    //para gravar a venda
    public void GravaVendaR(VendaModel vendM)
    {
        try
        {
            Conexao();
            con.Open();
            con.Execute(GravaVendaSQL, vendM, commandType: CommandType.Text);
            con.Close();
        }
        catch (Exception erro)
        { throw erro; }
    }

    //para buscar as vendas
    public List<VendaModel> BuscaVendaR()
    {
        try
        {
            Conexao();
            con.Open();
            IList<VendaModel> listar = SqlMapper.Query<VendaModel>(con, BuscaTodosSQL).ToList();
            return listar.ToList();
        }
        catch (Exception erro)
        { throw erro; }
    }
}

CONTROLLER

public class VendaController : Controller
{
    //
    // GET: /Venda/
    public ActionResult Index()
    {
        VendaRepositorio vendaRepo = new VendaRepositorio();
        return View(vendaRepo.BuscaVendaR());
    }

    //
    // GET: /Venda/Details/5
    public ActionResult Details(int id)
    {
        return View();
    }

    //
    // GET: /Venda/Create
    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Venda/Create
    [HttpPost]
    public ActionResult Create(VendaModel objVenda)
    {
        try
        {
            // TODO: Add insert logic here
            if (ModelState.IsValid)
            {
                VendaRepositorio vendaRepo = new VendaRepositorio();
                vendaRepo.GravaVendaR(objVenda);
                ViewBag.Messaga = "Dados gravados com sucesso!";
            }

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    //
    // GET: /Venda/Edit/5
    public ActionResult Edit(int id)
    {
        return View();
    }

    //
    // POST: /Venda/Edit/5
    [HttpPost]
    public ActionResult Edit(int id, FormCollection collection)
    {
        try
        {
            // TODO: Add update logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    //
    // GET: /Venda/Delete/5
    public ActionResult Delete(int id)
    {
        return View();
    }

    //
    // POST: /Venda/Delete/5
    [HttpPost]
    public ActionResult Delete(int id, FormCollection collection)
    {
        try
        {
            // TODO: Add delete logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}

VIEW INDEX

@model IEnumerable<LojaMVC5Dapper.Models.VendaModel>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.id_vd)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.id_pd)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.id_cl)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.data_vd)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.qtd_vd)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.id_vd)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.id_pd)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.id_cl)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.data_vd)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.qtd_vd)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

VIEW CREATE

@model LojaMVC5Dapper.Models.VendaModel



@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>




@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>VendaModel</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.id_vd, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.id_vd)
                @Html.ValidationMessageFor(model => model.id_vd)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.id_pd, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.id_pd)
                @Html.ValidationMessageFor(model => model.id_pd)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.id_cl, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.id_cl)
                @Html.ValidationMessageFor(model => model.id_cl)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.data_vd, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.data_vd)
                @Html.ValidationMessageFor(model => model.data_vd)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.qtd_vd, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.qtd_vd)
                @Html.ValidationMessageFor(model => model.qtd_vd)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

RESULTS [! [insert image description here][2][2]

inserir a descrição da imagem aqui

  • The field of select name_pd does not appear in the Vendamodel model and other tbm do not exist. Where does this class Sqlmapper come from? I use Dapper and do not need it, I simply use the method Connection.Query<Vendamodel>(sql); sql being the select...

  • Thanks @Fabio Lima! As for the visualization, it’s bringing everything you wanted. Already in "Create new", it’s still the same. The ID doesn’t go away, I can’t pick up a customer or a product that’s already registered and insert it into the new sale. How do I solve these problems? Thanks in advance.

  • When you execute this command: SqlMapper.Query<VendaModel>(con, BuscaTodosSQL).ToList(), is trying to bind to VendaModel of different data. What you have in select "Search Todossql" has to have the same properties as "Vendamodel", or you have to create another model that corresponds to select with Join.

  • OK @Ricardo! Thanks for the tip.

No answers

Browser other questions tagged

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