How else can I map decimals to doubles with EntityFramework POCOs?

908 Views Asked by At

I'm trying to refactor an an existing codebase to use POCO EF. Currently it uses EntityObjects but there is custom code to "flatten" the mapped objects to POCOs, i.e. for all mapped classes there are currently two related objects, one POCO called MyClass and one EntityObject called MyClassEF which has a single additional method with the signature MyClass Flatten(). This seems horrible, I know, but it has allowed a fairly straightforward mapping of what are decimal types in the database to double types in the model, because the conversion can take place in the Flatten() method.

Double types are used in code because they are considerably faster when performing analytical calculations, decimal types are probably used in the database because they seemed like a good idea at the time and the previous hand-rolled ORM didn't have the type-mapping restrictions that EF does. Unfortunately, simply changing the datatype in the database is now impractical because there are so many applications which use it (although most of them still convert the type to double, they still expect it to be decimal in the db).

So, currently I'm looking at modifying my model classes to have something like this :

private double _myDouble;
public double MyDouble { get { return _myDouble; } set { _myDouble = value; }
public decimal MyDouble_asDecimal { 
  get { return Convert.ToDecimal(_myDouble); }
  set { _myDouble = Convert.ToDouble(value); }
}

...which seems fairly unpleasant. Am I missing a blindingly obvious better way to do this?

1

There are 1 best solutions below

1
On

What about a simple extension method(s):

public static class MyExtension
{
    public static decimal ToDecimal(this double d)
    {
        return Convert.ToDecimal(d);
    }

    public static double ToDouble(this decimal d)
    {
        return Convert.ToDouble(d);
    }
}

So your models would remain unchanged and your flatten method just use customer.DoubleValueProperty.ToDecimal();

Not sure if this is what you want :-)

Also, if you are using mapping and flattening, I'd recommend having a look at automapper. Takes a lot of pain away.