首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EF7 DateTime“指定的转换无效”

EF7 DateTime“指定的转换无效”
EN

Stack Overflow用户
提问于 2016-03-24 10:30:49
回答 1查看 1.9K关注 0票数 0

我有一个ASP.NET核心项目在路上,我已经添加了EF7。

在Amazon RDS上使用SQL Server可以很好地工作,除非我将DateTime字段添加到模型中并将其迁移到数据库中。

然后,每次我重新启动项目并尝试获取实体(通过DBContext和Linq)时,我都会收到一个非常非常讨厌的异常消息。它不喜欢的DateTime值会是什么呢?

模型类:

代码语言:javascript
复制
public class Advertiser
{
    // ... Standard constructors go here

    [Key]
    public string Key { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public string Email { get; set; }
    public DateTime TargetDate { get; set; }
    public string Comments { get; set; }
}

上下文:

代码语言:javascript
复制
public class AdvertiserContext : DbContext
{
    public DbSet<Advertiser> Advertisers { get; set; }
}

Repository类中导致异常的代码行:

代码语言:javascript
复制
public Advertiser Find(string key)
{ 
    return Context.Advertisers.Single(x => x.Key == key);
}

出现两个“堆叠”异常,第一个:

代码语言:javascript
复制
Microsoft.Data.Entity.Query.Internal.QueryCompiler[1]
An exception occurred in the database while iterating the results of a query.
System.InvalidCastException: Specified cast is not valid.
at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,Microsoft.Data.Entity.Storage.ValueBuffer)

第二个是:

代码语言:javascript
复制
Microsoft.AspNet.Server.Kestrel[13]
An unhandled exception was thrown by the application.
System.InvalidCastException: Specified cast is not valid.
at (wrapper dynamic-method) System.Object:lambda_method (System.Runtime.CompilerServices.Closure,Microsoft.Data.Entity.Storage.ValueBuffer
EN

回答 1

Stack Overflow用户

发布于 2016-03-24 22:16:38

sql中的DateTime的最小值为1/1/1753 12:00:00 AM由于您的TargetProperty不可为空,我认为您的实体正被初始化为'0001/01/01 12:00:00 AM‘,这是DateTime在clr中的最小值,它超出了范围,因此出现异常。

您有两个选项来解决您的问题,一个是更改迁移方法或映射,并将列数据类型设置为DateTime2。另一种方法是将TargetDate声明为可空。下面是代码片段。

代码语言:javascript
复制
 modelBuilder.Entity<Advertiser>(entity =>
{    
    entity.Property(a => a.TargetDate)
                .ForSqlServerHasColumnType("DateTime2");
});

代码语言:javascript
复制
public DateTime? TargetDate { get; set; }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36192263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档