C#DateTime类和数据库中的日期时间

Spy*_*ros 0 c# sql database datetime sql-server-2005

我有以下问题.

我有一些的DateTime属性的对象,并在数据库中的表,我储存的所有对象,在SQL Server中我要存储日期时间数据类型的一些列的日期时间属性,但在SQL Server日期时间的格式是不同的c#中的DateTime类,我得到一个sql异常,说"无法解析DateTime".我知道如何通过使格式YYYY-MM-DD解决这个但这是正确的和最佳的解决方案,这样做吗?

public void UpdateInvitation(string ownerId, string couponKey, string status, string invitedEmail, DateTime? sentDate, DateTime? redeemedDate)
    {
        using (var con = new SqlConnection(this.ConnectionString))
        {
            try
            {
                con.Open();
                var command =
                        new SqlCommand(
                                "UPDATE INVITATIONS SET Status='@status', InvitedEmail='@invitedEmail', SentDate='@sentDate', RedeemDate='@redeemedDate' WHERE CouponKey='@CouponKey' AND OwnerId='@OwnerId'");
                var ownerIdParam = new SqlParameter("@ownerId", ownerId);
                var couponKeyParam = new SqlParameter("@couponKey", couponKey);
                var statusParam = new SqlParameter("@status", status);
                var invitedEmailParam = new SqlParameter("@invitedEmail", invitedEmail);
                var sentDateParam = new SqlParameter("@sentDate", sentDate.Value) { SqlDbType = SqlDbType.DateTime };
                var redeemedDateParam = new SqlParameter("@redeemedDate", redeemedDate.Value) { SqlDbType = SqlDbType.DateTime };
                command.Parameters.AddRange(new[]
                                            {
                                                    ownerIdParam, couponKeyParam, statusParam, invitedEmailParam,
                                                    sentDateParam, redeemedDateParam
                                            });
                command.Connection = con;
                var rowsAffected = command.ExecuteNonQuery();
                Log.DebugFormat("Invitation updated for owner id : [{0}] with key {1}, {2} rows affected", ownerId,
                                couponKey, rowsAffected);
            }
            catch (Exception exception)
            {
                throw new InvitationDataContextException(exception);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Art*_*hur 7

没有引号

new SqlCommand("UPDATE INVITATIONS SET Status=@status, InvitedEmail=@invitedEmail, SentDate=@sentDate, ...
Run Code Online (Sandbox Code Playgroud)