与一对一关系中的 FOREIGN KEY 冲突 Entity Framework Code First
Conflicted with the FOREIGN KEY in One to One Relationship Entity Framework Code First
虽然我要添加迁移没关系,但是当我要 运行 更新数据库时,我在包管理器控制台中收到此类错误
ALTER TABLE 语句与 FOREIGN KEY 约束冲突 "FK_dbo.ServiceTypes_dbo.Services_ServiceTypeID"。冲突发生在数据库 "Otaidea"、table "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; }
}
我的另一个Table:
public class ServiceType
{
[ForeignKey("Services")]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
public virtual Services Services { get; set; }
}
你模型中的关系是错误的。 Services 有一个 "Type",所以外键从 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
属性 做同样的事情,但是因为你没有 post 我让它保持原样。
此外,如果您删除数据库并让 Entity Framework 为您重新创建它会更好。因为你有一个错误的模型关系,事情变得 "messy"。
虽然我要添加迁移没关系,但是当我要 运行 更新数据库时,我在包管理器控制台中收到此类错误
ALTER TABLE 语句与 FOREIGN KEY 约束冲突 "FK_dbo.ServiceTypes_dbo.Services_ServiceTypeID"。冲突发生在数据库 "Otaidea"、table "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; }
}
我的另一个Table:
public class ServiceType
{
[ForeignKey("Services")]
public int ServiceTypeID { get; set; }
public string NAME { get; set; }
public virtual Services Services { get; set; }
}
你模型中的关系是错误的。 Services 有一个 "Type",所以外键从 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
属性 做同样的事情,但是因为你没有 post 我让它保持原样。
此外,如果您删除数据库并让 Entity Framework 为您重新创建它会更好。因为你有一个错误的模型关系,事情变得 "messy"。