使用 IDataReader 解决数据库差异的最佳实践

发布于 2024-07-25 20:59:13 字数 599 浏览 12 评论 0原文

我有一个简单的值对象,我用来自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挥剑断情 2024-08-01 20:59:13

我不知道 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.

慢慢从新开始 2024-08-01 20:59:13

你的想法是正确的方法。 也许更短:

short id = Convert.ToInt16(data[1]); //8 characters less

或者制作扩展方法。

public static short ToShort(this IDataReader r, int index)
{
    return Convert.ToInt16(r[index]);
}

现在你可以:

short id = data.ToShort(1); //18 characters less

:)

Your idea is the right way. Perhaps even shorter:

short id = Convert.ToInt16(data[1]); //8 characters less

Or make extension method.

public static short ToShort(this IDataReader r, int index)
{
    return Convert.ToInt16(r[index]);
}

Now you can:

short id = data.ToShort(1); //18 characters less

:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文