我有一个ASP.NET核心项目在路上,我已经添加了EF7。
在Amazon RDS上使用SQL Server可以很好地工作,除非我将DateTime字段添加到模型中并将其迁移到数据库中。
然后,每次我重新启动项目并尝试获取实体(通过DBContext和Linq)时,我都会收到一个非常非常讨厌的异常消息。它不喜欢的DateTime值会是什么呢?
模型类:
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; }
}上下文:
public class AdvertiserContext : DbContext
{
public DbSet<Advertiser> Advertisers { get; set; }
}Repository类中导致异常的代码行:
public Advertiser Find(string key)
{
return Context.Advertisers.Single(x => x.Key == key);
}出现两个“堆叠”异常,第一个:
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)第二个是:
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发布于 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声明为可空。下面是代码片段。
modelBuilder.Entity<Advertiser>(entity =>
{
entity.Property(a => a.TargetDate)
.ForSqlServerHasColumnType("DateTime2");
});或
public DateTime? TargetDate { get; set; }https://stackoverflow.com/questions/36192263
复制相似问题