[英]Getting an invalidcastexception when trying to retrieve data
When running the get method to return a view populated with details, I get the exception saying:当运行 get 方法返回填充了详细信息的视图时,我收到异常说:
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.DateTime'.'
The code code that does it is this:这样做的代码是这样的:
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);
}
I am not sure why it's trying to cast the object to a date type我不知道为什么它试图将对象强制转换为日期类型
My model looks like this:我的模型看起来像这样:
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; }
}
------------------Update------------------ - - - - - - - - - 更新 - - - - - - - - -
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");
});
-------------Update-------------- - - - - - - -更新 - - - - - - -
This is error is likely caused by a mismatch between the types in your database, and the types of your model.此错误可能是由数据库中的类型与模型的类型不匹配引起的。
Note : this can have many causes, depending on whether this is code first, newer .net core, forgetting to do a migration or ModelBuilder misdirection.注意:这可能有很多原因,这取决于这是代码优先、较新的 .net 核心、忘记进行迁移还是 ModelBuilder 错误定向。
The easiest fix is to make sure you have run the latest migration and updated the database, your model builder is correct.最简单的解决方法是确保您运行了最新的迁移并更新了数据库,您的模型构建器是正确的。 or that simply your data matches your types或者只是您的数据与您的类型相匹配
You have a really strange code, in your action, it reminds me a data reader, looks like you are trying to add an item from IQuerable to IList.您有一个非常奇怪的代码,在您的操作中,它让我想起了数据阅读器,看起来您正在尝试将 IQerable 中的项目添加到 IList。 Try this尝试这个
List<Booking> list = _airPortContext.Booking.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.