添加新行时无法添加或更新子行

Cannot add or update a child row when adding a new row

我已经看到 this answer 并正在使用它建议的解决方案,但仍然遇到相同的错误。

我有一个 Agency table,外键约束为 User Table,这是 Agency table:

CREATE TABLE agency (
    AgencyId                BIGINT          NOT NULL    AUTO_INCREMENT,
    UserId                  BIGINT          NOT NULL,
    AgencyName              VARCHAR(150)    NOT NULL,

    CONSTRAINT PK_Agency PRIMARY KEY(AgencyId),
    CONSTRAINT FK_Agency_User FOREIGN KEY (UserId) REFERENCES user (UserId) ON DELETE RESTRICT ON UPDATE RESTRICT
);

这是我的 Agency 实体:

[Table("agency")]
public class Agency
{
    public long AgencyId { get; set; }

    [Required]
    public long UserId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; } // <-- user Entity

    [Required]
    [StringLength(GlobalConstants.MaxLengthForLongName)]
    public string AgencyName { get; set; }
}

现在我想为现有用户添加新代理商:

public void AddOrUpdateAsAdminUser(Agency agency)
{
    if (agency.UserContact.UserId <= 0)
    {
        throw new Exception($"User: {agency.User.Email} does not exists");
    }

    if (agency.AgencyId > 0)
    {
        // update existing agency
        _context.Agency.Attach(agency);
        _context.Entry(agency).State = EntityState.Modified;
        _context.Entry(agency).Property(x => x.UserId).IsModified = false;
        _context.Entry(agency.User).State = EntityState.Detached; // <-- don't update User
    }
    else
    {
         // add new agency: exception is thrown here
        _context.Agency.Add(agency);
        _context.Entry(agency.User).State = EntityState.Detached; // <-- Don't update User
    }

    _context.SaveChanges();
}

_context.SaveChanges(); 行抛出以下异常:

"Cannot add or update a child row: a foreign key constraint fails (\"dbName\".\"agency\", CONSTRAINT \"FK_Agency_User\" FOREIGN KEY (\"UserId\") REFERENCES \"user\" (\"UserId\"))"

System.Exception {MySql.Data.MySqlClient.MySqlException}

您收到此错误是因为您正试图 add/update 根据当前存储在表 1 中的值,向代理行添加 UserID 字段没有有效值的行。

问题出在我的映射逻辑上,当将 AgencyViewModel 映射到 Agency 时,我只将 UserViewModel 映射到 User... 这意味着 UserId 是 0(未映射),当我想保存代理时。

[Table("agency")]
public class Agency
{
    public long AgencyId { get; set; }

    [Required]
    public long UserId { get; set; }  // <-- I was NOT mapping UserId

    [ForeignKey("UserId")]
    public User User { get; set; } // <-- I was mapping User

    [Required]
    [StringLength(GlobalConstants.MaxLengthForLongName)]
    public string AgencyName { get; set; }
}