![](/img/trans.png)
[英]InvalidCastException when getting data from Database as a datetime
[英]Getting an invalidcastexception when trying to retrieve data
当运行 get 方法返回填充了详细信息的视图时,我收到异常说:
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.DateTime'.'
这样做的代码是这样的:
public IActionResult GetBookings()
{
List<Booking> list = new List<Booking>();
foreach(var b in _airPortContext.Booking) // <--- Exceptions comes on this line
{
list.Add(b);
}
return View(list);
}
我不知道为什么它试图将对象强制转换为日期类型
我的模型看起来像这样:
public class Booking
{
public int BookingID { get; set; }
[Display(Name = "Class type")]
public int ClassLevel { get; set; }
[Display(Name = "From")]
public string FromDestination { get; set; }
[Display(Name = "To")]
public string ToDestination { get; set; }
[Display(Name = "From date")]
public DateTime FromDate { get; set; }
[Display(Name = "To date")]
public DateTime ToDate { get; set; }
[Display(Name = "Class")]
public ClassType TravelClass { get; set; }
}
- - - - - - - - - 更新 - - - - - - - - -
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
modelBuilder.Entity("Airport.Models.Booking", b =>
{
b.Property<int>("BookingID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("ClassLevel")
.HasColumnType("int");
b.Property<DateTime>("FromDate")
.HasColumnType("datetime2");
b.Property<string>("FromDestination")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("ToDate")
.HasColumnType("datetime2");
b.Property<string>("ToDestination")
.HasColumnType("nvarchar(max)");
b.Property<int>("TravelClass")
.HasColumnType("int");
b.HasKey("BookingID");
b.ToTable("Booking");
});
- - - - - - -更新 - - - - - - -
此错误可能是由数据库中的类型与模型的类型不匹配引起的。
注意:这可能有很多原因,这取决于这是代码优先、较新的 .net 核心、忘记进行迁移还是 ModelBuilder 错误定向。
最简单的解决方法是确保您运行了最新的迁移并更新了数据库,您的模型构建器是正确的。 或者只是您的数据与您的类型相匹配
您有一个非常奇怪的代码,在您的操作中,它让我想起了数据阅读器,看起来您正在尝试将 IQerable 中的项目添加到 IList。 尝试这个
List<Booking> list = _airPortContext.Booking.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.