如何解决这个问题:"Unable to cast object of type 'System.Collections.Generic.List`1[System.DateTime]' to type 'System.IConvertible'."

How to solve this issue: "Unable to cast object of type 'System.Collections.Generic.List`1[System.DateTime]' to type 'System.IConvertible'."

谁能帮我解决演员表的这个问题?这是我的代码。当我在开始使用(TaxiPlannerEntities)时使用断点时,它不会进入 foreach,而是直接进入捕获异常 e 并向我显示此错误。

 public class BookingController : Controller
    {
        /*[HttpPost]*/
       // [Route("InsertBooking")]
        public string Book(int employee_ID , List<DateTime> datebooked)
        {

            using (TaxiPlannerEntities contextx = new TaxiPlannerEntities())
            {
                try
                {
                    //Create new booking
                    var booking1 = new booking();
                    booking1.uid = employee_ID;

                    List<DateTime> y = new List<DateTime>();
                    y.Add(Convert.ToDateTime(datebooked));

                   /* y.Add(DateTime.Now);
                    y.Add(DateTime.Now.AddDays(1));
                    y.Add(DateTime.Now.AddDays(2));
                    y.Add(DateTime.Now.AddDays(3));*/
                   /* y.Add(Convert.ToDateTime(datebooked));*/


                    foreach (DateTime x in y)
                    {

                        var db1 = new booking_date
                        {
                            bookingDate = x
                        };
                        db1.status = "pending";
                        booking1.booking_date.Add(db1);

                    }

                    contextx.bookings.Add(booking1);
                    contextx.SaveChanges();

                    return "success";
                }

                catch (Exception e)

                {
               //     System.Diagnostics.Debug.WriteLine("test");
                    return e.Message;
                }
            }
        }
    }
}

您的 datebooked 变量已经是 List<DateTime>。不要尝试在其上使用 Convert.ToDateTime 然后将结果添加到 y (它不会工作;您不能将日期列表协调到单个日期)

从您的代码中删除对 y 的任何提及,并使用 datebooked 代替:

foreach(DateTime x in datebooked)

等等..

如果您只想使用 datebooked 列表中的日期之一(它的名称不是复数,这意味着您打算将其作为单个日期?)那么只需像索引一样索引列表数组并取例如第一个日期,或更改方法签名以便它取单个日期而不是日期列表


这一行看起来也有点奇怪:

booking1.booking_date.Add(db1);

如果您有一个 booking_date 个对象的集合,调用集合 BookingDates(复数)

会使代码更具可读性

您应该始终尝试将变量名称的复数形式与代码中的对象类型相匹配;集合应该是复数