本文介绍了EntityFramework:从实例化的“ System.String”类型到“ System.DateTime”类型的指定强制转换无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SP,正在借助 DbContext.Database SqlQuery 方法执行。我这样称呼它:

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

编辑1:-现在通过 DateTime

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();

最后一行抛出从 string DateTime 无效。

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

以下是SP的定义。

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

如果我直接在SQL Management Studio中执行SP,它将运行而不会出现任何问题:

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

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

这里出了什么问题?

推荐答案

spResult是什么? 作为参数?大概是日期时间吗?在这种情况下:给它一个 DateTime

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

var t = DateTime.Now;

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

如果错误与 SPResult有关-好吧,我们看不到它,所以很难评论:但是再次-映射SQL [n] [var] char(len | max)到C# string ,并将SQL datetime 映射到C# DateTime

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.

这篇关于EntityFramework:从实例化的“ System.String”类型到“ System.DateTime”类型的指定强制转换无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:18