当我要添加迁移时,这是可以的,但当我要运行更新数据库时,我在包管理器控制台中遇到了这种类型的错误
ALTER TABLE语句与FOREIGN KEY约束"FK_dbo.ServiceTypes_dbo.Services_ServiceTypeID"冲突。冲突发生在数据库"Otaidea"表"dbo.Services"列"ServicesID"中。
我的两种型号:
public class Services
{
[Key]
public int ServicesID { get; set; }
[DisplayName("Register Date")]
public DateTime RegisterDate { get; set; }
public int ServiceTypeID { get; set; }
public string ApplicationUserID { get; set; }
public virtual ServiceType ServiceType { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
我的另一张桌子:
public class ServiceType
{
[ForeignKey("Services")]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
public virtual Services Services { get; set; }
}
您在模型中的关系是错误的。服务有一个"类型",因此外键从ServiceType变为Service。您不需要在ServiceType 中引用服务
你应该这样创建你的模型:
服务
public class Services
{
[Key]
public int ServicesID { get; set; }
[DisplayName("Register Date")]
public DateTime RegisterDate { get; set; }
public string ApplicationUserID { get; set; }
[ForeignKey("ServiceType")]
public int ServiceTypeID { get; set; }
public virtual ServiceType ServiceType { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
服务类型
public class ServiceType
{
[Key]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
}
我也会对ApplicationUserID
属性做同样的事情,但由于你没有发布它,我就照原样发布。
此外,如果你放弃你的数据库,让实体框架为你重新创建它会更好。因为你有一个错误的模式关系,事情变得"一团糟"。