How to return an int in a Decimal property

1

I have a SQL string (made by another programmer a long time ago so I can not change it) which returns something like this: If it has value in the column, it returns the value, otherwise it returns 0 (I would post the SQL here but it's gigantic.)

However, column with value is decimal, without value is integer. To pass it to C #, I created a model with dynamic property:

public dynamic valorRetornado { get; set; }

But it comes null. I tried with object and also did not funfou.

Does anyone have any ideas?

@HarryPotter here is:

//Data é a string aonde está o SQL
var dados = db.Database.SqlQuery<Produtos>(data);
                    foreach (var itens in dados)
                    {                        
                        listaProdutos.Add(customer);
                    }
    
asked by anonymous 01.07.2014 / 15:41

2 answers

3

So you should put it like this:

public Decimal valorRetornado { get; set; }

The fact that I noticed that you are using a EntityFramework to generate the data.

Another thing if you are to return 0 ( Zero ) but this column can contain NULL

public Decimal? valorRetornado { get; set; }

and leave returns NULL , where it has no value.

Let's go with a simple example

I have in my database a table with these characteristics:

But,Iwanttoget3fieldsId,NomeandValorandcreateaclassonmysystemforthisusingEntityFrameworktoexecuteaSQLandbringthisdata:

ClassTemplate

publicclassExemplo{publicintId{get;set;}publicstringNome{get;set;}publicdecimal?Valor{get;set;}}

InthisclasstheValuefieldcancontainNullvalues,sameasthedefaultsettinginmydatabase,whichwillautomaticallyhandleEntityFramework.

Encoding:

IList<Exemplo>exemplos=db.Database.SqlQuery<Exemplo>("SELECT Id, Nome, Valor FROM Exemplos")
              .ToList<Exemplo>();

Note that the table field name and its type should match your class so you do not have problems and conversion errors

Data contained

Databrought,viaDebugVisualStudiotothecreatedmodelclass

Note that you have 3 items, and the Id number 2 Value is NULL equal to your database.

    
01.07.2014 / 15:53
1

Can not you handle everything for decimal ?? it is very dangerous to use type dynamic , if you end up forgetting about any treatment you will have exceptions ...

I do not know how you're doing to read from the database if it's with DataRow or EntityFramework , but here's a help ...

(!dr.IsNull("coluna") ? Convert.ToDecimal(dr["coluna"]) : 0.0m)

    
01.07.2014 / 15:47