如何最好地在数据库和web服务调用之间转换类型

本文关键字:调用 服务 之间 转换 类型 web 何最好 数据库 | 更新日期: 2023-09-27 18:01:42

我正在开发一个ASP。. Net c# web应用程序应该使用ODBC访问数据库,然后将获取的数据传递给web服务。

当我尝试使用Convert转换日期时,我面临一个问题。ToDateTime和parseDate来更改从数据库访问的日期的格式,并将其更改为web服务所需的合适格式。例如:

the database datetime storage format is "MM/dd/yyyy hh:mm:ss tt"
07/15/2011 03:05:10 pm
the webservice datetime storage format is "dd/MM/yyyy hh:mm:ss"
15/07/2011 15:00:00

如何更改和转换日期时间数据类型的这些不同格式,以便web服务正确地接受它?

另外,在web服务中有一个布尔数据类型,它在数据库中存储为整数,我如何处理它,以便web服务以正确的方式接受布尔数据类型?

例如:

the isGiven variable may have the value of 0 in database while it should be false or true in the web service as it accepts it as boolean only.
is there an implicit conversion between int and bool data types?

如何最好地在数据库和web服务调用之间转换类型

数据库日期时间存储格式为"MM/dd/yyyy hh: MM:ss tt"

不,它不是。数据库不将datetime值存储为格式化字符串,而是将其存储为表示时间点的数字。当你读取它时,你得到的是DateTime值,而不是string

要将DateTime值转换为dd/MM/yyyy hh:mm:ss格式,只需使用自定义格式字符串:

theDate.ToString("dd'/'MM'/'yyyy HH':'mm':'ss")

将整数转换为布尔值可以在从数据库中读取它时完成:

cast(isGiven as bit)

或之后:

reader["isGiven"] != 0

我可能过于简化了,但是在您写入数据库之前,您的web服务方法不能只是接受bool并将映射逻辑放入服务调用(或helper方法)中吗?

public void DoSomething(bool myBool)
{
    var myBoolConverted = myBool ? 1 : 0;
    myDatabase.DoSomething(myBoolConverted);
}

应该可以:

    string s = "07/15/2011 03:05:10 pm";
    // get database date / time
    DateTime dt = DateTime.ParseExact(s, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.GetCultureInfo("en-US"));
    // format as web service date / time
    string ws = dt.ToString("dd/MM/yyyy hh:mm:ss", CultureInfo.GetCultureInfo("en-US"));