[英]How else can I map decimals to doubles with EntityFramework POCOs?
I'm trying to refactor an an existing codebase to use POCO EF. 我正在尝试重构现有代码库以使用POCO EF。 Currently it uses EntityObject
s but there is custom code to "flatten" the mapped objects to POCOs, ie 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()
. 当前它使用EntityObject
但是有自定义代码将映射的对象“展平”到POCO,即,对于所有映射的类,当前有两个相关的对象,一个名为MyClass
POCO和一个名为MyClassEF
EntityObject
,具有一个带有签名的附加方法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. 我知道,这似乎很可怕,但是它允许将数据库中的十进制类型映射为模型中的双精度类型,这相当简单,因为转换可以在Flatten()
方法中进行。
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. 在代码中使用双精度类型是因为它们在执行分析计算时要快得多,在数据库中可能使用十进制类型,因为当时它们似乎是个好主意,并且以前的手动ORM没有类型映射限制EF做到了。 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). 不幸的是,现在更改数据库中的数据类型是不切实际的,因为使用它的应用程序太多了(尽管大多数应用程序仍将类型转换为双精度,但他们仍然希望它在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? 我是否错过了一个令人眼花obvious乱的更好的方法呢?
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();
因此,您的模型将保持不变,并且展平方法仅使用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 . 另外,如果您正在使用映射和展平,我建议您看一下automapper 。 Takes a lot of pain away. 减轻了很多痛苦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.