【发布时间】: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