1

I have an entity with a NrPeso decimal property that can be saved in the database as 0 or null. Here is what I'm doing to assign the value to the property:

entity.NrPeso = Convert.ToDecimal(object.value("value"))

The problem is: if I don't fill the object value, it's set to Nothing. When I do the cast it turns into 0. But I don't want 0, I want Nothing. If I compare the object value with Nothing it will return me Nothing if it is Nothing or 0.

I tought in a few alternatives but they don't seem good.

So, what is the right way to do this?

gabsferreira
  • 3,089
  • 7
  • 37
  • 61
  • If `NrPeso` is of Decimal type then it can't be assigned Null value anyway, so can't see the point here. – Shadow The GPT Wizard Oct 04 '12 at 14:00
  • _"I have an entity"_ means you're using Entity-Franmework? Then this is a duplicate of [How do I set a field to DBNull in Entity Framework](http://stackoverflow.com/questions/820752/how-do-i-set-a-field-to-dbnull-in-entity-framework) – Tim Schmelter Oct 04 '12 at 14:00

4 Answers4

4

Decimal is a structure - is cannot be Nothing by definition.

You need a nullable Decimal.

If NrPeso is defined as Nullable(Of Decimal) (aka Decimal?), things should work as you expect.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

If you want to distinguish between 0 and Nothing when using Decimal (or any other value type), you should use a nullable type in the first place.

So use Decimal? instead of Decimal

sloth
  • 99,095
  • 21
  • 171
  • 219
0

Try this:

Dim obj As Object = object.value("value")
entity.NrPeso = If (obj Is Nothing, Nothing, Convert.ToDecimal (obj))
Rolf Bjarne Kvinge
  • 19,253
  • 2
  • 42
  • 86
0

Instead of using Convert.ToDecimal, consider using Decimal.TryParse and then in a failure condition explicitly set the Nullable type to Null:

Dim outVal As Decimal?
If Decimal.TryParse(object.value("value"), outVal)
   entity.NrPeso = outVal
Else
   entity.NrPeso = Nothing
End If

Additionally, consider setting Option Strict On in your project to avoid type issues like this in the future.

Jim Wooley
  • 10,169
  • 1
  • 25
  • 43