EF Core 6 code first one to zero or one navigation

35 Views Asked by At

I have googled as well as searched SO for this extensively, to no avail.

    class Account 
    {
    [Key]
    [StringLength(80)]
    public string AccountID { get; set; }

    [StringLength(80)]
    public string Name { get; set; }

    [StringLength(80)]
    public string Email { get; set; }

    [ForeignKey("AccountID")]
    public virtual Address? Address { get; set; }
    }

    class Address
    {
    [Key]
    [StringLength(80)]
    public string AccountID { get; set; }

    [StringLength(80)]
    public string City { get; set; }

    [StringLength(80)]
    public string Street { get; set; }
    }

Address should be optional - if it's not there, the application should still work.

The migration builder seems to have the relationship between the tables inverted:

    migrationBuilder.CreateTable(
        name: "Account",
        columns: table => new
        {
            AccountID = table.Column<string>(type: "varchar(80)", maxLength: 80, nullable: false),
            Name = table.Column<string>(type: "varchar", nullable: true),
            Email = table.Column<string>(type: "varchar", nullable: true),
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Account", x => x.AccountID);
            table.ForeignKey(
                name: "FK_Account_Address_AccountID",
                column: x => x.AccountID,
                principalTable: "Address",
                principalColumn: "AccountID");
        });

Now when I try to insert data in the Account table, I am getting an error message about a conflict with a foreign key restraint in the Address table. It looks like there must already be a record in the Address table with the account id I am using to insert data in the Account table.

How do I fix this?

Hint: My fluent API does not offer .Optional() or .WithOptional().

0

There are 0 best solutions below