當運行 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");
});
- - - - - - -更新 - - - - - - -

uj5u.com熱心網友回復:
此錯誤可能是由資料庫中的型別與模型的型別不匹配引起的。
注意:這可能有很多原因,這取決于這是代碼優先、較新的 .net 核心、忘記進行遷移還是 ModelBuilder 錯誤定向。
最簡單的解決方法是確保您運行了最新的遷移并更新了資料庫,您的模型構建器是正確的。或者只是您的資料與您的型別相匹配
uj5u.com熱心網友回復:
你有一個非常奇怪的代碼,在你的操作中,它讓我想起了一個資料閱讀器,看起來你正試圖將一個專案從 IQerable 添加到 IList。嘗試這個
List<Booking> list = _airPortContext.Booking.ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324829.html
