C# 无法将int类型隐式转换为(namespace.model.class)类型
我有两个表service和Appointment我正在尝试将serviceId插入Appoints表,但serviceId类型(Int)和Appoints.service.Id(namespace.model.class)不同,因此错误是“无法将类型“Int”隐式转换为“namespace.model.class” 控制器:C# 无法将int类型隐式转换为(namespace.model.class)类型,c#,asp.net-mvc,C#,Asp.net Mvc,我有两个表service和Appointment我正在尝试将serviceId插入Appoints表,但serviceId类型(Int)和Appoints.service.Id(namespace.model.class)不同,因此错误是“无法将类型“Int”隐式转换为“namespace.model.class” 控制器: [HttpPost] ... if (ModelState.IsValid) { appointments = new Appoi
[HttpPost]
...
if (ModelState.IsValid)
{
appointments = new Appointments()
{
service = appointments.service.Id,
};
db.Appointments.Add(appointments);
db.SaveChanges();
}
return RedirectToAction("Index");
}
您正试图将对象分配给int类型的id。如果您的
约会
类中有外键,如ServiceId
则分配给它
appointments = new Appointments()
{
serviceid = appointments.service.Id,
};
或者,如果你没有那笔财产,那么你应该这样做
appointments = new Appointments()
{
service = appointments.service,
};
但是您的
约会.服务
不应为空。您的约会
实体应具有服务ID
外键(除了完整的实体关系服务
)。分配ServiceId。@StuartLC yes Appointments将ServiceId作为外键,Appointments.cspublic virtual Services service{get;set;}
我不太明白你想做什么-约会必须已经存在,这样你才能引用约会.service.id
,然后你试图将外键serviceId
分配给应该已经存在的东西,如果你已经从数据库中检索到约会的话在这种情况下,您可能无法将相同的约会再次添加到表中。您能否提供有关Appintmant类和服务类的更多详细信息?