Generate a Partial Model from a complete Model

Asked

Viewed 28 times

1

I have a Model called: Cliente_man that represents the customer register.

But this Model, has a lot of information, and to the screen that I am developing not ah need of all, so I would like to move to the View one Partial Model only with the data I need to use.

It follows below part of the code receiving the Model complete(Cliente_Man)

Controller:

    [ValidateInput(false)]
    public ActionResult DetailTabControl()
    {
        if (Session["cod_cli"] != null)
        {
            int codCliente = Convert.ToInt32(TempData["codCliente"]);

            Cliente_man model = db.Cliente_man.Find(codCliente);

            return PartialView("~/Views/Cliente_man/_DetailTabControl.cshtml", model);
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

View:

@model OneeWeb_v3.Models.Crm.Cliente_man
<h3>
    @Html.DisplayFor(model => model.razao_social).ToHtmlString()
</h3>

So I created a new Model called: Cliente_manDetalhes, which contains only the data I need.

I changed in the View:

@model OneeWeb_v3.Models.Crm.Cliente_manDetalhes
<h3>
    @Html.DisplayFor(model => model.razao_social).ToHtmlString()
</h3>

And in the Controller:

 [ValidateInput(false)]
    public ActionResult DetailTabControl()
    {
        if (Session["cod_cli"] != null)
        {
            int codCliente = Convert.ToInt32(TempData["codCliente"]);

            //Cliente_man model = db.Cliente_man.Find(codCliente);

            Cliente_manDetalhes mode = from s in db.Cliente_man
                                       where s.id_cliente == codCliente
                                       select new
                                       {
                                           id_cliente = s.id_cliente,
                                           nome_fantasia = s.nome_fantasia,
                                           Perfil = s.Perfil,
                                           n_doc = s.n_doc,
                                           cidade = s.cidade,
                                           siglaEstado = s.siglaEstado
                                       });

            return PartialView("~/Views/Cliente_man/_DetailTabControl.cshtml", model);
        }
        else
        {
            return RedirectToAction("Login", "Account");
        }
    }

But how do I retrieve information from Model Cliente_Man? To the above code returns the error:

Cannot implicity convert type 'System.Linq.IQueryable<<anonymous type:int id_cliente, string nome_fantasia, string Perfil, string n_doc, string cidade, string siglaEstado>>' to 'OneeWeb_v3.Models.Crm.Cliente_manDetalhes'. An explicit conversion exists

  • this cliente_mandetalhes 'and the same as Cliente_man ? your query returns the values for this module correctly? if yes just put (this Client) in front of the query

  • 1

    Thomas, please always add error messages as text and not as images. In addition to making it easier to read and improve the indexing of the question, it prevents people with external domain blocks from being able to read the entire post.

1 answer

4


There’s a lot of mistakes there.

For starters. This query

from s in db.Cliente_man
where s.id_cliente == codCliente
select new
{
    id_cliente = s.id_cliente,
    nome_fantasia = s.nome_fantasia,
    Perfil = s.Perfil,
    n_doc = s.n_doc,
    cidade = s.cidade,
    siglaEstado = s.siglaEstado
});

returns a list of objects of an anonymous type, once you used the keyword new and did not specify the type to be created.

You are trying to assign the query result to a variable of type Cliente_manDetalhes.

It would be possible to adapt the query to return a list of Cliente_manDetalhes, changing the instruction select for

select new Cliente_manDetalhes { ... }

The assignment would remain wrong because the return of that will be a collection of Cliente_manDetalhes and, in addition, the RU would not be able to create Cliente_manDetalhes.

Well, the solution is simple, you need to materialize the data before trying to do the mapping to Cliente_manDetalhes.

Since you need an item and not a collection, you can facilitate your query by using First/FirstOrDefault, but would need to do this mapping otherwise than using the method Select.

var item = db.Cliente_man.FirstOrDefault(s => s.id_cliente == codCliente);
var mode = new Cliente_manDetalhes
{
    id_cliente = item.id_cliente,
    nome_fantasia = item.nome_fantasia,
    Perfil = item.Perfil,
    n_doc = item.n_doc,
    cidade = item.cidade,
    siglaEstado = item.siglaEstado
};

If you make a point of using the method Select for this, you will need to adapt your query. It would be something like:

(from s in db.Cliente_man
where s.id_cliente == codCliente 
select s)  // #1 Consulta LINQ To Entities - Retorna uma lista de Cliente_man
.ToArray() // #2 Materialização da consulta em memória
.Select(s => new Cliente_manDetalhes
{
    ... // #3 Mapeamento da lista de Cliente_man para Cliente_manDetalhes
})
.FirstOrDefault(); #4 // Seleção do primeiro item

Browser other questions tagged

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