Specified conversion is not valid

Asked

Viewed 3,604 times

2

I’m making an appointment with LINQ in the DataTable in that code snippet. I have to check if a link already exists for a registered person in the database. My query using the LINQ is working perfectly, the problem is to store the query.Count() in a variable of type int.

I am using the version of Visual Studio 2010. I did the test in version 2013 and it worked normally. What could be done to store the value of query.Count() in a variable of type int or to use in if()?

//Retorna a relação dos Vinculos contida na base de dados 

DataTable PessoasVinculadas = Pessoa.ConsultarPessoasVinculadas(idPessoaReferenciada);
//Procura os registros existentes 
var query = PessoasVinculadas.AsEnumerable().Where(x => x.Field<int>("tipo") == TipoVinculo && x.Field<int>("pessoa_referenciada_id")
== idPessoaReferenciada && x.Field<int>("pessoa_vinculada_id") == idPessoaVinculada);
//Conta os registro existentes 
int cont = query.Count();

//Se registro for igual a 0 Adicionar 
if (cont == 0)
{
    //Cria Vinculo 
    Pessoa.Adicionar(TipoVinculo, idPessoaReferenciada, idPessoaVinculada);
}

Suggested Solution

 var query = PessoasVinculadas.AsEnumerable()
                         .Where(x => x.Field<int>("tipo") == TipoVinculo
                          && x.Field<int>("pessoa_referenciada_id") == idPessoaReferenciada
                          && x.Field<int>("pessoa_vinculada_id") == idPessoaVinculada).ToList();

                        int cont = query.Count;

Exception Message :

System.InvalidCastException was caught
  HResult=-2147467262
  Message=Conversão especificada não é válida.
  Source=System.Data.DataSetExtensions
  StackTrace:
       em System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
       em Gerencial.Formularios.Gestao.Licenca.ImportarPessoaVinculo.<>c__DisplayClass5.<backgroundWorker_DoWork>b__0(DataRow x) na C:\Users\mmurta\documents\visual studio 2010\Projects\Gerencial\Gerencial\Formularios\Gestao\Licenca\ImportarPessoaVinculo.cs:linha 240
       em System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
       em System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       em System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       em Gerencial.Formularios.Gestao.Licenca.ImportarPessoaVinculo.backgroundWorker_DoWork(Object sender, DoWorkEventArgs e) na C:\Users\mmurta\documents\visual studio 2010\Projects\Gerencial\Gerencial\Formularios\Gestao\Licenca\ImportarPessoaVinculo.cs:linha 239
  InnerException: 
  • What do you mean by 2010, 2013? You’re talking about VS. But it doesn’t matter, what matters is the language version or the . Net you’re using. Check this out: http://answall.com/q/21672/101. What’s the problem? I don’t see why it would work in one version and not in the other version.

  • sorry I forgot to mention rs , so I don’t know I did the same process I don’t know what might be wrong in this conversion .

  • 1

    And if you put an . Tolist() at the end of this query and use: query.Count, it works?

  • Laerte nein thus worked =\

  • 1

    An error occurs?

  • This keeps popping up: System.Invalidcastexception was Caught Message=Specified conversion is not valid.

  • The way I showed it also gives this error @stringname?

  • Yes, you want me to post the detailed error ?

  • Count already type whole, why are you doing cast?

  • @stringname Yes, please. Put the full error and the current code you are doing (but do not delete what is already in the question).

  • you that I post the error of which of the attempts ? that of To.list() already gives the error in the query..

  • To.list() already gives the error in the query

  • 1

    Your mistake is in x.Field<int> and not in the Count().

Show 8 more comments

2 answers

2

What could be done to store the query value. Count() in an int variable or to use in if()?

You can convert your query to a list and use the property Count

var count = PessoasVinculadas.AsEnumerable()
                             .Count(x => x.Field<int>("tipo") == TipoVinculo 
                              && x.Field<int>("pessoa_referenciada_id") == idPessoaReferenciada 
                              && x.Field<int>("pessoa_vinculada_id") == idPessoaVinculada);

EDIT

Your problem lies in the values within Count(), some value there is not integer, so the conversion error.

  • I tried but keeps popping up System.Invalidcastexception was Caught Message =Specified conversion is not valid.

  • But you’re doing some cast?

  • of the two ways you mentioned gave error , he launches the exception as soon as he executes

2


The mistake you’re having is not in the Count. Is here:

var query = PessoasVinculadas
                .AsEnumerable()
                .Where(x => x.Field<int>("tipo") == TipoVinculo && 
                            x.Field<int>("pessoa_referenciada_id") == idPessoaReferenciada && 
                            x.Field<int>("pessoa_vinculada_id") == idPessoaVinculada);

Some of these variables are not int. Check the conversions.

In addition, the test can be greatly simplified to:

if (!PessoasVinculadas
                .AsEnumerable()
                .Any(x => x.Field<int>("tipo") == TipoVinculo && 
                            x.Field<int>("pessoa_referenciada_id") == idPessoaReferenciada && 
                            x.Field<int>("pessoa_vinculada_id") == idPessoaVinculada))
{
    //Cria Vinculo 
    Pessoa.Adicionar(TipoVinculo, idPessoaReferenciada, idPessoaVinculada);
}

The performance of Count is normally less than Any, and you’re not wanting to tell, exactly. You want to know if there are no records, so Any fits better.

  • 1

    I was able to find the correct type using Pesoasvinculadas.Rows[index][columnIndex] Thanks a lot for the tip !

Browser other questions tagged

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