First in code. INSERT statement contradicts FOREIGN KEY constraint

I just started using the first Code approach to create databases. I have the following 3 tables:

public partial class AccountHolder
{
    public int AccountHolderId { get; set; }

    public virtual List<Address> Address { get; set; }
}

public partial class Nominee
{
    public int NomineeId { get; set; }

    public virtual List<Address> Address { get; set; }
}

public partial class Address
{
    public int AddressId { get; set; }

    public int AccountHolderId { get; set; }
    public AccountHolder AccountHolder { get; set; }

    public int NomineeId { get; set; }
    public Nominee Nominee { get; set; }
}

Here AccountHolderthey Nomineehave 1 to *replication with the address. The free API I used for this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>().HasRequired(p => p.AccountHolder)
                                      .WithMany(p => p.Address)
                                      .HasForeignKey(p => p.AccountHolderId)
                                      .WillCascadeOnDelete(false);
        modelBuilder.Entity<Address>().HasRequired(p => p.Nominee) 
                                      .WithMany(p => p.Address)
                                      .HasForeignKey(p => p.NomineeId)
                                      .WillCascadeOnDelete(false);
    }

Now my problem is, whenever I try to insert data into AccountHolder or Nominee, I get this exception:

In the case of installing AccountHolder

{"The INSERT statement contradicted the FOREIGN KEY restriction \" FK_dbo.Addresses_dbo.Nominees_NomineeId \ ". The conflict occurred in the database" CodeFirst.BankContext ", table" dbo.Nominees ", column" NomineeId ",. \ R \ nThe application has completed. }

In case of nominal insertion

{ " INSERT FOREIGN KEY \" FK_dbo.Addresses_dbo.AccountHolders_AccountHolderId\ ". " CodeFirst.BankContext ", " dbo.AccountHolders ", " AccountHolderId ",.\r\n ." }

Cananybody, , , ?

+3
2

Nominees_NomineeId, Nominee.You Nominee, AccountHolder.

+4

dbo.AccountHolders dbo.Nominees, . FK , , .

SQL Server Management Studio, sp_help 'dbo.dbo.Nominees'. , FK, . . sp_help 'dbo.dbo.AccountHolders'.

, .

+1

Source: https://habr.com/ru/post/1527710/


All Articles