在EF6中使用Code First技术
当我声明我的DateTime属性时:
Public Property StartDate As DateTime
我收到此错误:
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.
当我将声明更改为:
Public Property StartDate As Nullable(Of DateTime)
一切都很好。
我不明白为什么。我在其他SO帖子中看到我们需要将DateTime2与SQL一起使用,但我不知道这意味着什么。它不是代码中的类型。这是我应该设置的其他东西吗?
我是使用nullable
声明获取快捷方式还是在EF流程中自动更改为datetime2
?
答案 0 :(得分:1)
您可能希望创建自定义EF约定并将其插入以指示Entity Framework如何处理DateTime的每个属性。
创建以下约定类。
public class DateTime2Convention : Convention
{
public DateTime2Convention()
{
this.Properties<DateTime>()
.Configure(c => c.HasColumnType("datetime2"));
}
}
然后在继承DbContext的类中为覆盖OnModelBuilder方法的约定集合添加自定义约定。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// existing code, if any
modelBuilder.Conventions.Add(new DateTime2Convention());
}
您可能需要查看Entity Framework Custom Code First Conventions (EF6 onwards)以获取更多信息。