我仍在学习EF Core,并且在尝试仅将用户数据(没有BusinessUserProfile和BusinessCompany)插入数据库时遇到错误。我有以下表格:User,BusinessUserProfile和BusinessCompany。关系是:用户具有一个BusinessUserProfile,BusinessCompany具有多个BusinessUserProfile。
我的课程是这样创建的:
用户模型类别:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public BusinessUserProfile BusinessUserProfile { get; set; }
public User()
{
BusinessUserProfile = new BusinessUserProfile();
}
}
BusinessUserProfile模型类别:
public class BusinessUserProfile
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public BusinessCompany BusinessCompany { get; set; }
public int BusinessCompanyId { get; set; }
public User User { get; set; }
public int UserId { get; set; }
}
}
BusinessCompany模型类别:
public class BusinessCompany
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BusinessUserProfile> BusinessUserProfiles { get; set; }
public BusinessCompany()
{
BusinessUserProfiles = new Collection<BusinessUserProfile>();
}
}
DataContext.cs:
modelBuilder.Entity<User>()
.HasOne(u => u.BusinessUserProfile)
.WithOne(bup => bup.User)
.HasForeignKey<BusinessUserProfile>(bup => bup.UserId);
modelBuilder.Entity<BusinessCompany>()
.HasMany(bc => bc.BusinessUserProfiles)
.WithOne(bup => bup.BusinessCompany)
.HasForeignKey(bup => bup.BusinessCompanyId);
将用户添加到数据库时,出现错误:
MySqlException:无法添加或更新子行:外键约束失败(
mydb
。businessuserprofiles
,CONSTRAINT FK_BusinessUserProfiles_BusinessCompanies_BusinessCompanyId
外部键(BusinessCompanyId
)参考businesscompanies
(id
)删除C)。有人可以建议我吗?
最佳答案
此类错误通常是由于子表具有指向由于某种原因而不再存在的父记录的外键记录而引起的。在您的特定情况下,通常意味着BusinessUserProfile
表中存在一个或多个记录,这些记录指的是BusinessCompany
表中不再存在的记录。
这是一个查询,您可以运行该查询以标记一些孤立的子记录:
SELECT *
FROM BusinessUserProfile bup
WHERE NOT EXISTS (SELECT 1 FROM BusinessCompany bc
WHERE bc.id = bup.BusinessCompanyId);
如果此查询显示记录,则说明您的观察结果。如果没有,那么至少您可以排除这种可能性。