在 Code-First Entity Framework 和 SQL Server 中使用 DateTime 属性
我有一个示例类 book
:
public class Book
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateAdded { get; set; }
}
当我尝试将新的 book
添加到 BookDb
上下文时......
using (BookDb db = new BookDb())
{
Book book = new Book {
Name = "Some name",
DateAdded = DateTime.Now
};
db.Books.Add(book);
db.SaveChanges();
}
... 抛出错误:
System.Data.SqlClient.SqlException:datetime2数据的转换 类型转换为日期时间数据类型导致值超出范围。这 声明已终止。
我发现造成此问题的原因是 .NET 和 SQL Server 之间的 datetime
类型不兼容。有一种方法可以告诉 EF 在传统实体框架中使用 SQL Server 格式,但是如何在代码优先实体框架中执行此操作?
我在 . NET 4(MVC 3 Web 应用程序)和 SQL Server 2008 Express。
I have an example class book
:
public class Book
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateAdded { get; set; }
}
When I attempt to add a new book
to the BookDb
context...
using (BookDb db = new BookDb())
{
Book book = new Book {
Name = "Some name",
DateAdded = DateTime.Now
};
db.Books.Add(book);
db.SaveChanges();
}
... an error is thrown:
System.Data.SqlClient.SqlException: The conversion of a datetime2 data
type to a datetime data type resulted in an out-of-range value. The
statement has been terminated.
I've found that the cause of this is the incompatible datetime
types between .NET and SQL Server. There is a way to tell EF to use SQL Server's format in traditional Entity Framework, but how do I do it in Code-First Entity Framework?
I am using EF4 on .NET 4 (MVC 3 web app) and SQL Server 2008 Express.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 Fluent API 中指定类型:
这会在数据库中创建一个
datetime2(7)
列。如果您想微调精度,可以使用:... 对于数据库中的
datetime2(0)
列。但是,您在问题中显示的代码是有效的,因为
datetime
类型允许存储早至 1750 年左右的日期。该异常仅发生在更早的日期。此异常的一个常见原因是未初始化的DateTime
属性,因为它表示年份 0001,无法存储在 SQL Server 中的datetime
列中。没有相应的属性来用数据注释来定义它。这只有使用 Fluent API 才能实现。
You can specify the type in Fluent API:
This creates a
datetime2(7)
column in the database. If you want to finetune the precision you can use:... for a
datetime2(0)
column in the DB.However, the code you have shown in your question works because the
datetime
type allows to store dates back to around 1750. The exception occurs only for earlier dates. A common reason for this exception is an uninitializedDateTime
property because it represents the year 0001 which can't be stored in adatetime
column in SQL Server.There is no corresponding attribute to define this with data annotations. It's only possible with Fluent API.
保存日期时需要填充一个值。这就是您收到此错误的原因。
只需使用
DateTime?
。不需要上面的魔法。When saving a date it needs to have a value populated. Thats why you get this error.
Just use
DateTime?
. There is no need for the magic above.您可以使用 datetime2 类型注释类的属性。
You can annotate the attribute of your class with the type datetime2.
如果启用了迁移,您还可以在那里调整内容。
If migrations are enabled you can also adjust stuff right there.