[英]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.