使用 IDataReader 解决数据库差异的最佳实践
我有一个简单的值对象,我用来自 IDataReader 的数据填充该对象(可能是对 Oracle 或 MS SQL 数据库的查询结果)。 该对象的工厂方法如下所示:
internal static SomeClass CreateFromDataReader(IDataReader data)
{
string message = data.GetString(0);
short id = data.GetInt16(1);
DateTime dateStamp = data.GetDateTime(2);
return new SomeClass(message, id, dateStamp);
}
然后我遇到了一个问题,该问题与 Oracle 和 MS SQL 数据库用于该特定列的数据类型的差异有关:在 Oracle 中,数据类型是数字,而对于MS SQL 使用的数据类型是smallint。
现在,虽然我可以通过执行以下操作来“解决”这个问题:
short id = Convert.ToInt16(data.GetValue(1));
是否有更好或更优雅的方法来做到这一点?
I have a simple value object which I populate with data from an IDataReader (could be the result of a query to either an Oracle or MS SQL database). The factory method for this object looks something like the following:
internal static SomeClass CreateFromDataReader(IDataReader data)
{
string message = data.GetString(0);
short id = data.GetInt16(1);
DateTime dateStamp = data.GetDateTime(2);
return new SomeClass(message, id, dateStamp);
}
I then ran into a problem which is related to the difference in the data type that the Oracle and MS SQL databases use for that particular column: in Oracle that data type is number while for MS SQL the data type used is smallint.
Now, while I could 'fix' this problem by doing something like the following:
short id = Convert.ToInt16(data.GetValue(1));
is there a better or more elegant way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道 ORM 如何处理这种情况。
但是,您应该使用可以容纳此类字段的两种(所有)情况的类型。
我查看了此表 & 看来十进制是您可以使用的适当的 .net 数据类型。
I don't know how ORMs take care of such a scenario.
However, you should use a type that can accomodate both (all) cases for such a field.
I looked at this table & it seems decimal is the appropriate .net data type you could use.
你的想法是正确的方法。 也许更短:
或者制作扩展方法。
现在你可以:
:)
Your idea is the right way. Perhaps even shorter:
Or make extension method.
Now you can:
:)