Problems with types and conversions when filling a page

Asked

Viewed 2,031 times

1

That is the mistake:

An exception of type 'System.InvalidCastException' occurred in App_Web_fjskumyk.dll but was not handled in user code

Additional information: Não é possível converter um objeto do tipo 'System.Collections.Generic.List`1[<>f__AnonymousType5`2[System.String,System.String]]' no tipo 'System.Collections.Generic.List`1[Ruptura.Models.MontaArvoreAcao]'.

I have tried everything and still not walking much in my code. See what I did in my Controller that returns the data:

var _listaUnidade = (
                             from r in db.Ruptura
                             join a in db.Apresentacao on r.Codigo_Apresentacao equals (a.Codigo_Apresentacao)
                             join m in db.Motivo on r.IDMotivo equals (m.IDMotivo)
                             where r.IDMotivo != 6

                             select new 
                             {
                                 a.Codigo_Unidade_Negocio,
                                 a.Unidade_Negocio
                             }).ToList().Distinct();

            ViewData["ListaUn"] = _listaUnidade.ToList();

Now at the moment of filling the page, is giving the stick. See my foreach in View, which is with the problems already cited.

......
<ul>
                                    @foreach (var un in (List<Ruptura.Models.MontaArvoreAcao>) ViewData["ListaUn"])
                                    {  
                                        <li item-checked='false' item-expanded='false'>
                                            @un.Unidade_Negocio

                                        </li>
                                    }
                                </ul>
......

So it gave no more error, but distinct it did not work.

var _listaUnidade = (
                             from r in db.Ruptura
                             join a in db.Apresentacao on r.Codigo_Apresentacao equals (a.Codigo_Apresentacao)
                             join m in db.Motivo on r.IDMotivo equals (m.IDMotivo)
                             where r.IDMotivo != 6

                             select new MontaArvoreAcao
                             {
                                 Codigo_Unidade_Negocio = a.Codigo_Unidade_Negocio,
                                 Unidade_Negocio = a.Unidade_Negocio
                             }).ToList().Distinct();

            ViewData["ListaUn"] = _listaUnidade.ToList();

I tried to make a similar one to that select(That works distinct)

select distinct a.Unidade_Negocio, r.IDMotivo

from Ruptura r
join Apresentacao a on a.Codigo_Apresentacao = r.Codigo_Apresentacao
join Motivo m on r.IDMotivo = m.IDMotivo

group by r.IDMotivo,a.Unidade_Negocio

order by r.IDMotivo

The way below I’m practically us finally, just a problem I don’t know where it comes from. For example, I have 5 Reasons listed. This is correct. For Idmotivo(1,2 and 3) I have 3 UN(Dermocosmetics, MIP and Generics). He is only listing me 2 UN for each Reason. The ID = 4 motif, I have only two UN(Generic and MIP) and Motif ID = 5 I have 3 UN(Generic, MIP and Dermocosmetics). It turns out that only 2 UN(Generic and MIP) is coming for everyone. Is there anything else missing? Here’s my code.

Model:

public static List<MontaArvoreAcao> CriarListaArvoreAcao()
        {
            RupturaEntities db = new RupturaEntities();

              var _listaUnidade = (
                                       from r in db.Ruptura
                                       join a in db.Apresentacao on r.Codigo_Apresentacao equals (a.Codigo_Apresentacao)
                                       join m in db.Motivo on r.IDMotivo equals (m.IDMotivo)
                                       where r.IDMotivo != 6

                                       select new MontaArvoreAcao
                                       {
                                           Codigo_Unidade_Negocio = a.Codigo_Unidade_Negocio,
                                           Unidade_Negocio = a.Unidade_Negocio,
                                           IDMotivo = r.IDMotivo
                                       }

                                  ).ToList().Distinct().DistinctBy(d => d.Codigo_Unidade_Negocio).DistinctBy(s => s.IDMotivo);

            return _listaUnidade.ToList();
        }

My Controller:

public ActionResult Acao()
        {
            ViewData["ListaUn"] = MontaArvoreAcao.CriarListaArvoreAcao();

            return View(MontaArvoreAcao.montaArvoreAcao());
        }

My View:

<ul>
                    @foreach (var item in Model)
                    {
                        if (_motivo != @item.Motivo)
                        {
                            _idmotivo = @item.IDMotivo;
                            <li item-checked='false' item-expanded='false'>
                                @item.Motivo

                                <ul>
                                    @foreach (var un in (List<Ruptura.Models.MontaArvoreAcao>) ViewData["ListaUn"])
                                    {
                                        <li item-checked='false' item-expanded='false'>
                                            @un.Unidade_Negocio

                                        </li>
                                    }
                                </ul>
                              </li>
                            }
                            _motivo = @item.Motivo;
                        }
                </ul>
  • It seems your problem is in select new , because you’re only going for two fields, and in the view you’re saying that viewData is a certain type of data (Rupture.Models.Montaarvoreacao)

  • If I declare my _list();

  • If you delete select and distinct shows results? Correct repeat?

  • As I gave a new Montaarvoreacao, I had to say that a certain field of this class is equivalent to a certain field of Linus. When this was done, the error disappeared, but the performance fell to unbearable levels. Since I started writing this commentary, I haven’t opened the page.

  • The distinct didn’t work. I tried to make it so it didn’t repeat the same UN and repeated, so it was slow.

  • Yes, it was just to try. But it presented data, correct?

  • I made an issue, to show how it is and what I want.

  • @pnet As you are updating the question, it turns out that the answer may be outdated as well. The initial problem was the error, now it seems that you have a problem in the query. I recommend to update the question with the new question, open another question and keep your original question.

  • Okay, it is that we are finding solutions throughout the help of colleagues, that we do not even notice and end up changing the course of the original post. But I already asked another question yes.

Show 4 more comments

2 answers

1

Unable to convert _list.Tolist() to a list of type Breakage.Models.Montaarvoreacao.

An alternative: In his Model Breakage.Models.Montaarvoreacao you could create a method Creatlistaarvoreacao for example, you will receive the _list.Tolist() and create your Tree list.

This is probably coming from a list of Strings you need to convert to the type you need List<Ruptura.Models.MontaArvoreAcao>.

Following this reasoning you would replace:

ViewData["ListaUn"] = _listaUnidade.ToList();

For:

//O método CriarArvoreAcao recebe o retorno do seu método para montar a lista
ViewData["ListaUn"] = MontaArvoreAcao.CriarListaArvoreAcao(_listaUnidade.ToList());

In the class of his Model you would implement the method:

public class MontaArvoreAcao
{
   ...
   //Passe _listaUnidade.List() como parâmetro desse método
   public static List<MontaArvoreAcao> CriarListaArvoreAcao(...)
   {
      //Esse método receberia o tipo retornado por _listaUnidade.List()
      //como parâmetro e retornaria uma lista do tipo List<MontaArvoreAcao>
   }

   ...
}

Alternative: Change your query by returning the type, in case Montaarvoreacao.

Change where you were:

select new 
{
   Codigo_Unidade_Negocio = a.Codigo_Unidade_Negocio,
   Unidade_Negocio = a.Unidade_Negocio
}).ToList().Distinct();

To:

select new MontaArvoreAcao
{
   Codigo_Unidade_Negocio = a.Codigo_Unidade_Negocio,
   Unidade_Negocio = a.Unidade_Negocio
}).ToList().Distinct();

Tip 1: First, it’s not interesting to do this query that returns.

The main idea of the MVC framework is to separate the different responsibilities, i.e., "Controllers" only interpret the user’s actions and make calls to Model. The Model yes, should perform this type of consultation, but I will not prolong, stay the tip.

Tip 2: In your "Where r.Idmotivo != 6" this number 6 can lead to future maintenance difficulties. Whoever reads your code has no idea what it means.

  • That’s Idmotivo, it’s a sequential int. It’s the value of Idmotivo, I don’t see how to do it differently.

  • @pnet Thinking of a few possibilities: You could create a method like Get motivox() that returns the Reason, or a Get motivox() method by only returning the Idreason, where X would be the Reason name. This will make your code more readable and when the person reads your code will understand better.

  • I know Renan, that there are several ways to improve and do different. I’m the one who has doubts on how to do. What I’m doing is a tree, almost a binary tree or is, I don’t know, and there’s a little bit more of a tarimba, knowledge, you know,?

  • But you’re right, I’m running a Titanic, which brings me many fields, when I use only one. I will do that yes, and a method for each field I use, always using the ID of the previous one. I hope it improves performance.

  • @pnet I understand, I put these possibilities/tips so you can adjust later if you want. But, specifically attacking the problem raised, try to create a method that will receive this _list.List() as a parameter and convert this _list.List() as suggested in the reply.

  • I took your suggestion, and I put that whole rule inside the Models and left the controller just calling the methods and returning to the View. I just haven’t figured it all out yet. Distinct on Inq is not working and query works.

Show 1 more comment

0

//Form 1 //Include at the beginning of your View a type for it: @model List

//In the controller: Return View(Montaarvoreacao.Create tree())

//does not need Viewdata. in the view this mode query is read directly as: @foreach (var un in Model) { //code }

//Form 2. //Include at the beginning of your View a type for it: @model Rupture.Models.Montaarvoreacao

//In the model: public List List { get; set; }

//In the controller: Montaarvoreacao model = new Montaarvoreacao(); model. List = model.Increasuretree(); Return View(model)

//does not need Viewdata. in the view this mode query is read directly as: @foreach (var un in Model.List) { //code }

//Note: the word "Model" is reserved for the object in which it represents the type of /your View.

//Hope you helped.

Browser other questions tagged

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