【发布时间】:2016-03-24 22:16:38
【问题描述】:
我有一个 ASP.NET Core 项目在路上,我已经添加了 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
【问题讨论】:
-
请包含您的相关型号/代码
-
在添加新的日期字段之前您有现有数据吗?也许这些行的日期为空值,如果是这样,请尝试填充空行
-
很好的猜测,但我使用示例数据进行了测试,并在测试之间将表放入数据库中。好像和新列的添加没有关系,一开始就没有空值。
-
“一个非常非常讨厌的异常消息” 我知道这显然很讨厌,但是在您的问题中提供该消息将大大有助于使这个问题得到回答。 .
-
刚刚添加了例外。上面的亚历克斯把它们删掉了。显然太讨厌了……所以,妥协。我只是包括了相关部分。
标签: entity-framework asp.net-core