开发者

How best to convert types between database and web service call?

开发者 https://www.devze.com 2023-03-19 05:29 出处:网络
I am developing an ASP.Net C# web application that should ac开发者_开发知识库cess the database using ODBC then pass the gotten data to a web service.

I am developing an ASP.Net C# web application that should ac开发者_开发知识库cess the database using ODBC then pass the gotten data to a web service.

I face a problem in converting date as I tried using Convert.ToDateTime and parseDate to change the format of the dates acccessed from the database and change it to the suitable formate needed for the web service. for example:

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

How I can change and convert these different formats for datetime data types so that the web service accepts it properly?

Also, there is a boolean data type in the web service which is stored as integer in the database, how I can handle that so that the web service accepts the boolean data type in a correct way?

for example:

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?


the database datetime storage format is "MM/dd/yyyy hh:mm:ss tt"

No, it's not. The database doesn't store the datetime value as a formatted string, it stores it numerically representing a point in time. When you read it you get it as a DateTime value, not a string.

To convert the DateTime value to the format dd/MM/yyyy hh:mm:ss you just use a custom format string:

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

Converting an integer to a boolean can either be done when you read it from the database:

cast(isGiven as bit)

or afterwards:

reader["isGiven"] != 0


I may be over-simplifying, but couldn't your web service method just accept a bool and put the mapping logic inside the service call (or a helper method) before you write to the database?

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

    myDatabase.DoSomething(myBoolConverted);
}


This should work:

    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"));
0

精彩评论

暂无评论...
验证码 换一张
取 消