【问题标题】:cannot implicitly convert type int to (namespace.model.class) type不能将 int 类型隐式转换为 (namespace.model.class) 类型
【发布时间】:2019-12-19 11:26:27
【问题描述】:

我有两个表 service 和 Appointments 我试图将 serviceId 插入 Appointments 表,但是 serviceId 类型(Int)和约会.service.Id(namespace.model.class)所以错误是“无法隐式转换类型” int' 到 'namespace.model.class'

控制器:

 [HttpPost]
 ...
     if (ModelState.IsValid)
     {
         appointments = new Appointments()
         {
             service = appointments.service.Id,
         };

         db.Appointments.Add(appointments);
         db.SaveChanges();
     }
     return RedirectToAction("Index");
 }

【问题讨论】:

  • 您的Appointments 实体应该有一个ServiceId 外键(除了完整的实体关系Service)。分配 ServiceId。
  • @StuartLC 是 Appointments 有 ServiceId 作为外键,Appointments.cs public virtual Services service { get; set; }
  • 我不太明白你想要做什么 - appointments 必须已经存在才能让你能够引用 appointments.service.id,然后你试图分配外键serviceId 到应该已经存在的东西,如果您已经从数据库中检索到约会。在这种情况下,您可能无法再次Add 同一个约会。
  • 您能否详细介绍您的 Appintmant 类和服务类?

标签: c# asp.net-mvc


【解决方案1】:

您正在尝试将对象分配给 int 类型的 id。如果您的 Appointments 类中有外键,例如 ServiceId,请分配给它。

appointments = new Appointments()
         {
             serviceid = appointments.service.Id,
         };

或者,如果您没有该属性,那么您应该这样做

appointments = new Appointments()
         {
             service = appointments.service,
         };

但你的appointment.service 不应该为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 2013-06-12
    • 1970-01-01
    • 2013-05-23
    • 2011-12-24
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多