如何在wcf uri模板中传递datetime2(0)?

时间:2015-12-24 10:12:23

标签: c# sql wcf datetime datetime2

我希望传递一些值也包括日期时间。我正在尝试这种方式,但我收到此错误“将数据类型nvarchar转换为datetime2时出错。”

这是我的功能;

public string InsertRezervation(int GarageId, int MemberId, string StartDate, string EndDate, bool isFinish)
        {
            SqlConnection connection = null;
            SqlCommand command = null;
            int rowsAffected = 0;

            string format = "yyyyMMdd";
            DateTime startDate = new DateTime(2014, 12, 18);
            DateTime endDate = new DateTime(2014, 12, 25);
            if (StartDate != null && EndDate != null)
            {
                startDate = DateTime.ParseExact(StartDate, format, CultureInfo.InvariantCulture);
                endDate = DateTime.ParseExact(EndDate, format, CultureInfo.InvariantCulture);
            }
            connection = new SqlConnection(conn);
            connection.Open();
            command = new SqlCommand("Parking.Rezervation", connection);
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.Parameters.Add("@PGarageId", System.Data.SqlDbType.NVarChar).Value = GarageId;
            command.Parameters.Add("@PMemberId", System.Data.SqlDbType.NVarChar).Value = MemberId;
            command.Parameters.Add("@PStartDate", System.Data.SqlDbType.NVarChar).Value = startDate;
            command.Parameters.Add("@PEndDate", System.Data.SqlDbType.NVarChar).Value = endDate;
            command.Parameters.Add("@PIsFinish", System.Data.SqlDbType.NVarChar).Value = isFinish;
            command.CommandText = "Parking.Rezervation";
            rowsAffected = command.ExecuteNonQuery();
            connection.Close();
            return string.Format("You entered: {0}", rowsAffected.ToString());

        }

这是界面;

[OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, 
        UriTemplate = "/InsertRezervation?GarageId={GarageId}&MemberId={MemberId}&StartDate={StartDate}&EndDate={EndDate}&isFinish={isFinish}")]
        string InsertRezervation(int GarageId, int MemberId, string StartDate, string EndDate, bool isFinish);

我该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

您正在使用DateTime类型传递SqlDbType.NVarChar值。将它们更改为SqlDbType.DateTime2喜欢;

command.Parameters.Add("@PStartDate", SqlDbType.DateTime2).Value = startDate;
command.Parameters.Add("@PEndDate", SqlDbType.DateTime2).Value = endDate;

如果GarageIdMemberId适用于您的列类型,也会更改为SqlDbType.IntisFinishSqlDbType.Bit。不要对所有这些使用NVarChar

还可以使用using statement自动处理您的连接和命令,而不是手动调用Close方法。