我还在学习EF Core,并且在尝试仅将用户数据(没有BusinessUserProfile和BusinessCompany)插入数据库时遇到错误。我有以下表:User,BusinessUserProfile和BusinessCompany。关系是User有一个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
FOREIGN KEY(BusinessCompanyId
)REFERENCES businesscompanies
(id
)ON DELETE C) 。
任何人都可以告诉我这个吗?
这种类型的错误通常是在子表具有指向父记录的外键记录时引起的,该记录由于某种原因不再存在。在您的特定情况下,它通常意味着BusinessUserProfile
表中有一个或多个记录指的是BusinessCompany
表中不再存在的记录。
这是一个查询,您可以运行以标记一些孤立的子记录:
SELECT *
FROM BusinessUserProfile bup
WHERE NOT EXISTS (SELECT 1 FROM BusinessCompany bc
WHERE bc.id = bup.BusinessCompanyId);
如果此查询显示记录,则说明您的观察结果。如果没有,那么至少你可以排除这种可能性。
你在User
班制作了所需的BusinessUserProfile
。因此,如果您尝试创建没有现有BusinessUserProfile
的用户,就像尝试插入null fk一样。你不允许的。