【问题标题】:How to solve this issue: "Unable to cast object of type 'System.Collections.Generic.List`1[System.DateTime]' to type 'System.IConvertible'."如何解决此问题:“无法将 'System.Collections.Generic.List`1[System.DateTime]' 类型的对象转换为 'System.IConvertible' 类型。”
【发布时间】:2019-10-29 05:48:21
【问题描述】:

谁能帮我解决这个演员表问题?这是我的代码。当我在 using(TaxiPlannerEntities) 开始时使用断点时,它不会进入 foreach,而是直接进入 catch 异常 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;
                }
            }
        }
    }
}

【问题讨论】:

  • 使用 Console.WriteLine(e.StackTrace);在 catch 子句中查找导致异常的行。
  • 您正尝试将整个List&lt;DateTime&gt; 转换为Convert.ToDateTime(datebooked),将转换结果添加单个元素到另一个List&lt;DateTime&gt;。这种转换应该达到什么目的?
  • @Arphile 我已经尝试过了,但它没有显示该行导致异常
  • y中有没有数据。 y 中的数据计数是多少?

标签: c# api entity-framework-6


【解决方案1】:

您的datebooked 变量已经是List&lt;DateTime&gt;。不要尝试在其上使用Convert.ToDateTime,然后将结果添加到y(这不起作用;您不能将日期列表与单个日期一致)

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

foreach(DateTime x in datebooked)

等等..

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


这条线看起来也有点奇怪:

booking1.booking_date.Add(db1);

如果您有一个booking_date 对象的集合,调用集合BookingDates(复数)会使代码更具可读性

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多