【问题标题】:Getting an invalidcastexception when trying to retrieve data尝试检索数据时获取 invalidcastexception
【发布时间】:2021-12-05 22:52:27
【问题描述】:

当运行 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");
                });

----------更新--------------

【问题讨论】:

  • 您是否将任何内容从字符串更改为日期时间而不进行迁移。表定义是什么?
  • 对不起,我是新手。我将添加由“添加迁移”创建的表定义。我希望这可能会有所帮助
  • 我刚刚运行了“add-migration addBookingToDatabase”,这是最新的
  • 你能进入 sql server 或你使用的任何东西并获得实际的表定义。我对数据库中的实际类型感兴趣。
  • 您将列类型指定为datetime2,但它在数据库中存储为nvarchar(max),这很奇怪。也许尝试使用普通的datetime 并检查它是否有效

标签: c# asp.net-mvc visual-studio entity-framework asp.net-core


【解决方案1】:

此错误可能是由于数据库中的类型与模型的类型不匹配造成的。

注意:这可能有很多原因,取决于这是代码优先、较新的 .net 核心、忘记进行迁移还是模型构建器方向错误。

最简单的解决方法是确保您已运行最新的迁移并更新了数据库,您的模型构建器是正确的。或者只是您的数据与您的类型匹配

【讨论】:

  • 我删除了数据库并重新运行“add-migration ...”。我的问题是我将类型从字符串更改为 DateTime,但在数据库中,这种类型仍然是字符串(nvarchar)类型而不是日期类型,这导致了错误
【解决方案2】:

你有一个非常奇怪的代码,在你的操作中,它让我想起了一个数据阅读器,看起来你正试图将一个项目从 IQuerable 添加到 IList。 试试这个

List<Booking> list = _airPortContext.Booking.ToList();

【讨论】:

  • 好点,但不是问题的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多