从字符串转换日期和/或时间时转换失败。 System.Data.Entity.Core.EntityCommandExecutionException

时间:2018-03-15 07:55:11

标签: c# sql api

我收到错误$exception {"An error occurred while reading from the store provider's data reader. See the inner exception for details."} System.Data.Entity.Core.EntityCommandExecutionException

内部异常说InnerException {"Conversion failed when converting date and/or time from character string."} System.Exception {System.Data.SqlClient.SqlException}

我正在使用的网址是2466:api / fullmessage / company / WaterMeter / 2017-03-01 / 2018-04-01

这是我正在使用的代码:

public List<FullMessage> GetByCompanyTypeBetweenDays(string id, string type, string day1, string day2)
    {
        DateTime Day1;
        DateTime Day2;
        if (!DateTime.TryParse(day1, out Day1))
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }
        if (!DateTime.TryParse(day2, out Day2))
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        };
        using (IoTdatabaseEntities entities = new IoTdatabaseEntities())
        {
            return entities.Database.SqlQuery<FullMessage>(@"SELECT *
            FROM [Messages] join [Devices] on [Devices].[DeviceID] = [Messages].[DeviceID]
            Where [devices].[company] = '@company' and [messages].[type] = '@type' and
            [Messages].[MessageSentDateTime] between '@FirstDay' AND '@LastDay'
            Order by [Messages].[MessageSentDateTime]
            ", new SqlParameter("company", id), new SqlParameter("type", type), new SqlParameter("FirstDay", Day1.ToString("yyyyMMdd")),new SqlParameter("LastDay",Day2.ToString("yyyyMMdd"))).ToList();
        }
    }

我尝试删除ToString("yyyyMMdd")方法,但这仍然给了我错误

public List<FullMessage> GetByCompanyTypeBetweenDays(string id, string type, string day1, string day2)
    {
        DateTime Day1;
        DateTime Day2;
        if (!DateTime.TryParse(day1, out Day1))
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }
        if (!DateTime.TryParse(day2, out Day2))
        {
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        };
        using (IoTdatabaseEntities entities = new IoTdatabaseEntities())
        {
            return entities.Database.SqlQuery<FullMessage>(@"SELECT *
        FROM [Messages] join [Devices] on [Devices].[DeviceID] = [Messages].[DeviceID]
        Where [devices].[company] = '@company' and [messages].[type] = '@type' and
        [Messages].[MessageSentDateTime] between '@FirstDay' AND '@LastDay'
        Order by [Messages].[MessageSentDateTime]
        ", new SqlParameter("company", id), new SqlParameter("type", type), new SqlParameter("FirstDay", Day1), new SqlParameter("LastDay", Day2)).ToList();
        }
    }

有人可以告诉我我做错了什么。当我在数据库中执行它时,查询有效。

在这篇文章中,他们删除了日期周围的引号,这根本不会返回任何内容 Handling date in SQL Server

0 个答案:

没有答案