0

I have the following query in C# using FluentData ORM.

List<dynamic> results = 
   Context().Sql(@"SELECT DISTINCT
                      a.EnteredDate,
                      bb.PK_EmployeeName,
                      bb.EmployeeId,
                      bb.EmployeeName,
                      dd.PK_EquipmentName,
                      dd.EquipmentId,
                      dd.EquipmentName
                   FROM 
                      dbo.PIT_Inspection a
                   INNER JOIN 
                      dbo.PIT_EmployeeName bb ON a.FK_EmployeeName = bb.PK_EmployeeName
                   INNER JOIN 
                      dbo.PIT_EquipmentName dd ON a.FK_EquipmentName = dd.PK_EquipmentName
                   WHERE 
                      CAST(a.EnteredDate AS DATE) BETWEEN '@0' AND @1'", 
                  fromDate, toDate ).QueryMany<dynamic>();

The parameters fromDate and toDate are strings and come populated with the following:

  • fromDate = "20150224"
  • toDate = "20150227"

The area that seems to give me problem is:

WHERE CAST(a.EnteredDate AS DATE) BETWEEN '@0' AND '@1'", 
   fromDate , toDate

I'm receiving an error

Conversion failed when converting date and/or time from character string

The above line, a.EnteredDate is of type DateTime. The query I'm executing, if copied over to SQL Server Management Studio, it runs fine. I double checked that my parameter is indeed bringing in correct data, as string.

Any idea on what causes this error?

4

1 回答 1

2

Most ORM's convert @ parameters into SqlParameter objects, which handle typing for you so you don't need to enclose your query variables in apostrophes to denote a string.

So change

'@0' AND @1'

to

@0 AND @1

This likely applies to FluentData, and definitely applies to PetaPoco, and EntityFramework.

于 2015-02-19T20:52:36.987 回答