How to convert Float to String using LINQ for Entity?

Asked

Viewed 454 times

1

How to convert Float to String using LINQ to Entity?

I need to convert a field from my database that has the float type to the string type in my C# using the LINQ.

Try using Convert.Tostring,

 ChaveArquivo = Convert.ToString(n.scanIma.Imagem), 

but this generates the following query in SQL.

CONVERT(NVARCHAR(30), [t0].[Imagem], 2)

returning the value 8.125000000000000e+003, whereas in the flock the original value is 8125, want converts to string of the same value "8125".

This is possible to do directly in the database with the function Str( [t0].[Imagem]).

I need an equivalent at LINQ.

My consultation;

using (var dm = DataContextFactory.GetContext(pacoteUsuario.Usuario))
{
    var consulta = (from docsCol in dm.Tabela_DocsColetivas
                    join doc in dm.Tabela_Documentos on docsCol.Apol_coletiva equals doc.Apol_coletiva
                    join scanIma in dm.Tabela_ScanImagens on new { Documento = doc.Documento, Alteracao = doc.Alteracao } equals new { Documento = scanIma.Documento.GetValueOrDefault(), Alteracao = scanIma.Alteracao.GetValueOrDefault() }
                    join tip in dm.Tabela_TiposImagens on scanIma.Cod_tipoimg equals tip.Cod_tipoimg into ti
                    from tipImag in ti.DefaultIfEmpty()
                    join ProdSubs in dm.Tabela_ProdutosSubs on doc.Cod_sub equals ProdSubs.Cod_sub into ps
                    from ProdSub in ps.DefaultIfEmpty()
                    select new
                    {
                        scanIma,
                        doc,
                        tipImag,
                        docsCol,
                        ProdSub,
                    })
                    .AsQueryable();

    var arquivos = consulta
        .Select(n => new ListaArquivos
        {
            NumeroContrato = n.docsCol.Apolice,
            NumeroApolice = n.doc.Apolice,
            NumeroFatura = n.doc.Endosso,
            CodSubGrupo = n.ProdSub.Cod_sub,
            NomeSubGrupo = n.ProdSub.Descricao,
            Competencia = String.Concat(n.doc.Mes_producao, "/", n.doc.Ano_producao),
            DescrArquivo = n.scanIma.Descricao,
            TipoImagem = Convert.ToDouble(n.tipImag.Tipo_uso),
            DescrTipoImagem = n.tipImag.Descricao == null ? string.Empty : n.tipImag.Descricao,
            ChaveArquivo = Convert.ToString(n.scanIma.Imagem),
        });

    this.listaArquivos.AddRange(arquivos.ToList());
    listArquivos.Add(this);
    return listArquivos;
}

Class List files

namespace SistemasSeguros.COL.View.Webservice.Parâmetros
{
    public class ListaArquivos
    {
        public string NumeroContrato { get; set; }
        public string NumeroApolice { get; set; }
        public string NumeroFatura { get; set; }
        public double? CodSubGrupo { get; set; }
        public string NomeSubGrupo { get; set; }
        public string Competencia { get; set; }
        public string DescrArquivo { get; set; }
        public double? TipoImagem { get; set; }
        public string DescrTipoImagem { get; set; }
        public string ChaveArquivo { get; set; }
    }
}
  • The value in the bank is only 8125?

  • No, this is just the first value of this field in the scanIma table.

  • It would have to put the full amount?

  • @Randrade, this value is the real value that is in the first row of this column, there are more columns with different values, but for this column/row the value is only this, always are integer values, but the field was created with float.

  • Not quite that. I mean it got confused. You say it returns the value 8.125000000000000e+003, but is making the conversion of what value to arrive at this? I ask this because there are several ways to make this conversion, and even the CultureInfo can influence. But without knowing the original value, it becomes a little more difficult to see what really happened.

  • I think it would be simpler if you specified the original value, as you are doing the conversion (you have already said ChaveArquivo = Convert.ToString(n.scanIma.Imagem)) and the expected value (which also said it is 8125)

  • edited the question,

  • I have the answer below, but I expect something more convenient, ie a single function that makes the Convert for the expected type.

  • You can do a few tricks to solve, but the solution is to change the type and will not always work as expected. float is not accurate. Because it cannot be the conversion and has to be the Str()?

  • @bigown, not necessarily Str(), but a function that is able to convert the float to string. FUNCTION GENERATED BY THE ENTITY FRAMEWORK. as I mentioned in the question Convert.Tostring() launches in the database CONVERT(NVARCHAR(30), [t0].[Image], 2) this two at the end and the one generating the number 8.12500000000e+003.

  • @Randrade, now that I understand the meaning of question, the answer is yes, this 8125 is the real number in the database and complementing the field is always an integer value, however the ZÉ who created the table had the audacity to use a FLOAT, for a PK field.

  • @Gokussjgod I think my answer does what you want. And I’m talking about accuracy error.

  • I would like to know why the -1, so that I can improve the question,

Show 8 more comments

2 answers

12


You can use the SqlFunctions.StringConvert(), it will be converted to proper SQL code:

ChaveArquivo = StringConvert(n.scanIma.Imagem)

I put in the Github for future reference.

This answers the question directly. But it does not solve the problem shown in the comments.

The problem is that the guy float has no ability to give accuracy. Already I answered about it in several questions here. The problem cannot be solved any other way. And the worst thing is that it seems to solve in some cases. This is a danger because it causes the feeling of security that does not exist. Of course it may only be used in situations that gambiarras solve. But it is not possible to solve all cases. If the exact information is not available there is no guarantee that you will get it, no matter what algorithm you use.

  • 2

    As the documentation indicates namespace is System.Data.Objects.SqlClient who is in the Assembly System.Data.Entity.

  • Well, then I don’t know how you are using it. In the documentation there is no such exception as a possible one, so the problem must be somewhere else.

  • @Gokussjgod You added the DLL System.Data.Entity? She usually stays in C: Program Files Reference Assemblies Microsoft Framework.Netframework v4.0 or in EF6

2

I was able to solve the problem using two conversions one for Toint64 and one for Tostring.

var arquivos = consulta
            .Select(n => new ListaArquivos
            {
                NumeroContrato = n.docsCol.Apolice,
                NumeroApolice = n.doc.Apolice,
                CodSubGrupo = n.ProdutosSub.Cod_sub,
                NomeSubGrupo = n.ProdutosSub.Descricao,
                Competencia = n.doc.Mes_producao + '/' + n.doc.Ano_producao,
                DescrArquivo = n.scanIma.Descricao,
                TipoImagem = Convert.ToDouble(n.tipoImag.Tipo_uso),
                DescrTipoImagem = n.tipoImag.Descricao,
                ChaveArquivo = Convert.ToString(Convert.ToInt64(n.scanIma.Imagem)),
            });

Browser other questions tagged

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