简体   繁体   English

尝试检索数据时出现 invalidcastexception

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

相关问题 从数据库获取数据作为日期时间时出现 InvalidCastException - InvalidCastException when getting data from Database as a datetime 尝试从MongoDB中检索数据时获取“TimeoutException” - Getting “TimeoutException” when trying to retrieve data from MongoDB 尝试将Type强制转换为接口时,为什么会收到“ InvalidCastException:指定的强制转换无效”的信息 - Why am I getting an “InvalidCastException: Specified cast is not valid.” when trying to cast a Type to interface 尝试使用Linq在Entity Framework Code First中实现排序时获取InvalidCastException - Getting InvalidCastException when trying to implement sorting in Entity Framework Code First using Linq 将SQL Server ROWVERSION放入System.Data.Linq.Binary属性时,出现System.InvalidCastException - System.InvalidCastException when getting SQL Server ROWVERSION into System.Data.Linq.Binary property 尝试从Azure检索数据时出现MobileServiceInvalidOperationException - MobileServiceInvalidOperationException When Trying To Retrieve Data From Azure 尝试将列添加到dataGridView1,但出现异常InvalidCastException - Trying to add column to dataGridView1 but getting exception InvalidCastException 共享数据并添加到ObservableCollection时出现InvalidCastException - InvalidCastException when sharing data and adding to ObservableCollection 尝试从.bin文件读取时,InvalidCastException / Serialization异常 - InvalidCastException/Serialization Exception when trying to read from .bin file 尝试从xml文件创建列表时出现InvalidCastException - InvalidCastException when trying to make a list from xml file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM