如何解决此问题:“无法将类型为'System.Collections.Generic.List`1 [System.DateTime]'的对象转换为类型为'System.IConvertible'。”

时间:2019-10-29 05:48:21

标签: c# api entity-framework-6

有人可以帮我解决此问题吗?这是我的代码。当我在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;
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的datebooked变量已经是List<DateTime>。请勿尝试在其上使用Convert.ToDateTime,然后将结果添加到y(这是行不通的;您不能将日期列表与单个日期协调起来)

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

foreach(DateTime x in datebooked)

以此类推。

如果您只想使用datebooked列表中的日期之一(它的名称不是复数形式,是否意味着您打算将它设为单个日期?),则只需像数组一样对列表进行索引并例如采用第一​​个日期,或更改方法签名,以便采用单个日期而不是日期列表


这行看起来也有些奇怪:

booking1.booking_date.Add(db1);

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

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