EntityFramework : The specified cast from a materi

2019-08-04 17:40发布

问题:

I have a SP which I am executing with help of SqlQuery method of DbContext.Database. I am calling it as follows:

EDIT 1:- passing DateTime now

var t = form["datetime"];//value is 2013-May-08 09:30
DateTime dtm;
if (!DateTime.TryParse(t, out dtm))//successfully parses
     dtm = new DateTime(2013, 05, 8, 9, 30, 0);
var rTime= new SqlParameter("@rTime", dtm);
var result = UoW.ExecuteSp<SPResult>("spResult @rTime", rTime).ToList();

The last line throws the exception that specified cast from string to DateTime is not valid.

Following is the definition of SP.

ALTER PROC [dbo].[spResult]
(
    @rTime SMALLDATETIME --VARCHAR(32)
)
AS
BEGIN
--OTHER CODE
END

If I directly execute the SP in SQL Management Studio it runs without any problem:

EXEC spResult ='2013-May-08 09:30'

In SP the string is converted to date time as follows:

@resultAt SMALLDATETIME = CAST(@rTime AS SMALLDATETIME)

What is going wrong here?

回答1:

What does spResult take as a parameter? Presumably it is a datetime? In which case: give it a DateTime:

var t = DateTime.Now;

or

var t = new DateTime(2013,5,8,9,30,0); // 8 May 2013, 9:30am

If the error relates to SPResult - well, we can't see that so it is hard to comment: but again - map SQL [n][var]char(len|max) to C# string, and map SQL datetime to C# DateTime.