如何解决c#和sql server中的datetime问题 [英] how to resolve the problem of datetime in c# and sql server

查看:320
本文介绍了如何解决c#和sql server中的datetime问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户的及时插入到sql server db中,但事情就是当我点击时间按钮时它会抛出以下错误..



错误:将nvarchar数据类型转换为smalldatetime数据类型导致超出范围的值



和我的c#代码如下。



I am trying to insert the in-time of a user into sql server db but the thing is when i click on in time button it is throwing following error..

Error: The conversion of a nvarchar data type to a smalldatetime data type resulted in an out-of-range value

and my c# code is follows..

string sql1 = "insert into Attendance(UserId,InTime,Dated) values({0},{1},{2});" + " SELECT SCOPE_IDENTITY();";
                    result = (int)db.Database.SqlQuery<decimal>(sql1, new object[] { UserId, DateTime.Now.ToString("HH:MM:MM"), DateTime.Now.ToString("d") }).FirstOrDefault();

推荐答案

也许你必须删除
DateTime.Now.ToLongTimeString() 

进入

into

DateTime.Now()





因为你的数据类型列inTime是smalldatetime,你不能使用ToLongTimeString()



because you data type column inTime is smalldatetime, you can't use ToLongTimeString()


为什么????



您为什么直接在Entity Framework中发布此类声明?模型中是否没有可以解决的实体?为什么你第一次使用EF?



但是如果你坚持这种方法,请看看这里: http://www.inforbiro.com/blog-eng/entity-framework-how-to -use-datetime-in-esql-query / [ ^ ]



您还有其他选择:如果您想执行在上下文之外的东西,你可以从中提取ADO连接字符串,并使用常规的ADO方法。看看这里: http://stackoverflow.com/questions/13003797/get-the -entity-framework-connection-string [ ^ ]
Why????

Why are you issuing this kind of statement directly in Entity Framework? Is there no entity in the model you can address? Than why are you using EF on the first hand?

But if you stick to this approach, have a look here: http://www.inforbiro.com/blog-eng/entity-framework-how-to-use-datetime-in-esql-query/[^]

You have an other option though: if you want to execute something outside the context, you can extract the ADO connection string from it, and use regular ADO approach for that. Have a look here: http://stackoverflow.com/questions/13003797/get-the-entity-framework-connection-string[^]


这篇关于如何解决c#和sql server中的datetime问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆