【问题标题】:Error : Cannot add or update a child row: a foreign key constraint fails错误:无法添加或更新子行:外键约束失败
【发布时间】:2019-04-01 10:39:30
【问题描述】:

我仍在学习 EF Core,但在尝试仅将用户数据(没有 BusinessUserProfile 和 BusinessCompany)插入数据库时​​遇到错误。我有以下表格:用户、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)。

谁能给我建议?

【问题讨论】:

    标签: mysql ef-core-2.0


    【解决方案1】:

    这种类型的错误通常是由于子表的外键记录指向的父记录由于某种原因不再存在。在您的特定情况下,这通常意味着 BusinessUserProfile 表中有一条或多条记录,它引用了 BusinessCompany 表中不再存在的记录。

    这是一个查询,您可以运行它来标记一些孤立的子记录:

    SELECT *
    FROM BusinessUserProfile bup
    WHERE NOT EXISTS (SELECT 1 FROM BusinessCompany bc
                      WHERE bc.id = bup.BusinessCompanyId);
    

    如果此查询出现记录,则说明您的观察结果。如果不是,那么至少可以排除这种可能性。

    【讨论】:

      【解决方案2】:

      您在User 类中创建了所需的BusinessUserProfile。因此,如果您尝试创建一个没有现有 BusinessUserProfile 的用户,就像尝试插入一个空 fk。这是你不允许的。

      【讨论】:

      • 感谢您的回复。你能指出我在哪个地方设置了不允许 null BusinessUserProfile 吗?无论如何设置它可以为空?
      • 只需从 User 类中删除 BusinessProfile。或者添加一个属性int?用户类中的 BusinessProfileId。 learnentityframeworkcore.com/conventions/…
      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 2014-05-10
      • 2022-12-10
      • 2020-10-04
      相关资源
      最近更新 更多