我在Visual Studio 2012开发C#程序中使用实体框架。我想在数据库表中添加记录。记录(对象)包括属性(TRANSACTION_DATE),该属性不允许NULL值,并且它是DateTime格式。在数据库中,我的目标是这种格式:
yyyy-MM-dd HH:mm:ss.fff
所以我想将当前日期和时间传递给它,我的代码是这样的:
newEntry.TRASACTION_DATE = DateTime.ParseExact(DateTime.Now.ToString(),
"yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
但这给了我错误:
datetime2数据类型到datetime数据类型的转换导致超出范围的值。
我想知道为什么它没有转换成我想要的格式?
约束:
You shouldn't think about the database as storing the values in a particular string format at all - any more than it stores numbers as decimal or hex.
Instead, you should just view it as a date/time, e.g.
// TODO: Do you really want the local time, rather than UtcNow?
// TODO: Change TRANSACT_DATE to be TransactionDate ideally, to follow
// .NET naming conventions
newEntry.TRANSACT_DATE = DateTime.Now;
When you retrieve the value, you should get a DateTime
at that point too. Then if you want to display the value to the user you can apply a particular format. Different users may well want different formats - and may even want to display the same date/time in different time zones.
It's important to differentiate between the intrinsic data you store (in this case a date/time) and the text format that happens to be used to display it any one particular context/application. You should avoid conversions to/from strings at any time when you don't really need one. Ideally, these should only be at the boundaries of your application - e.g. when displaying text to a user, or potentially serializing to JSON or XML. Whenever an API allows you to not perform a conversion (e.g. with a database parameter) you should avoid it.
至于您当前的错误-是否有可能是您未填充的其他字段,因此正在使用default(DateTime)
,这将超出范围吗?这很有道理-但DateTime.Now
实际上不应超出范围,除非您已应用了单独的约束,或者您的系统时钟距离很远。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句