在Code-First Entity Framework和SQL Server中使用DateTime属性 [英] Using DateTime properties in Code-First Entity Framework and SQL Server

查看:493
本文介绍了在Code-First Entity Framework和SQL Server中使用DateTime属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例类

public class Book
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime DateAdded { get; set; }
}

当我尝试添加一个新的 / code>到 BookDb 上下文...

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

...抛出错误:


System.Data.SqlClient.SqlException :将datetime2数据
类型转换为datetime数据类型导致out-范围值。
语句已被终止。

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.






我发现这是因为.NET和SQL Server之间的不兼容的 datetime 类型。有一种方法来告诉EF在传统实体框架中使用SQL Server的格式,但如何在代码优先实体框架中执行此操作?


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?

我在.NET 4(MVC 3 Web应用程序)和SQL Server 2008 Express上使用EF4。

I am using EF4 on .NET 4 (MVC 3 web app) and SQL Server 2008 Express.

推荐答案

您可以在Fluent API中指定类型:

You can specify the type in Fluent API:

modelBuilder.Entity<Book>()
    .Property(f => f.DateTimeAdded)
    .HasColumnType("datetime2");

这将创建一个 datetime2(7)列在数据库中。如果你想确定你可以使用的精度:

This creates a datetime2(7) column in the database. If you want to finetune the precision you can use:

modelBuilder.Entity<Book>()
    .Property(f => f.DateTimeAdded)
    .HasColumnType("datetime2")
    .HasPrecision(0);

...一个 datetime2(0)列。

但是,您在问题中显示的代码的工作原理是因为 datetime 类型允许将日期存储到1750年左右。仅在较早的日期出现异常。这个异常的一个常见原因是未初始化的 DateTime 属性,因为它表示不能存储在 datetime 列。

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 uninitialized DateTime property because it represents the year 0001 which can't be stored in a datetime column in SQL Server.

没有相应的属性用数据注释来定义它。只能使用Fluent API。

There is no corresponding attribute to define this with data annotations. It's only possible with Fluent API.

这篇关于在Code-First Entity Framework和SQL Server中使用DateTime属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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