Cannot insert entity with null foreign key

entity-framework entity-framework-core

Question

Idea: Key entity, that can be replaced by other key, if that happens they get their FK's pointing to each other.

public class Key {
    string Id;
    string ReplacesId;
    Key Replaces;
    string ReplacedById;
    Key ReplacedBy;
}

Fluent mapping

modelBuilder.Entity<Key>().HasOne(k => k.Replaces)
    .WithOne()
    .HasForeignKey<Key>(k => k.ReplacesId)
    .IsRequired(false);

modelBuilder.Entity<NagKey>().HasOne(k => k.ReplacedBy)
    .WithOne()
    .HasForeignKey<NagKey>(k => k.ReplacedById)
    .IsRequired(false);

Problem: Trying to save an entity, it fails with duplicate foreign key error (which is null) as follows:

System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Keys' with unique index 'IX_Keys_ReplacedById'. The duplicate key value is (). The statement has been terminated.

1
0
2/18/2019 11:48:10 AM

Popular Answer

Solved by making indexes not unique:

modelBuilder.Entity<Key>()
    .HasIndex(x => x.ReplacedById)
    .IsUnique(false)
    .HasFilter(null);

modelBuilder.Entity<Key>()
    .HasIndex(x => x.ReplacesId)
    .IsUnique(false)
    .HasFilter(null);
0
2/18/2019 12:18:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow