Skip to content

The change of a navigation to a new instance and removing the old instance throws an Exception #29356

@JakobFerdinand

Description

@JakobFerdinand
Entities and DbContext
sealed class MyDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder
            .UseSqlServer("Server=localhost;Database=EfCore_TempKeySample_Sample;Integrated Security=true;TrustServerCertificate=True");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Author>(b =>
        {
            b.HasOne(a => a.AuthorsClub)
                .WithMany()
                .HasForeignKey(a => a.AuthorsClubId);
        });
        modelBuilder.Entity<Book>(b =>
        {
            b.HasOne(book => book.Author)
                .WithMany()
                .HasForeignKey(book => book.AuthorId);
        });
    }

    public DbSet<Author> Authors { get; set; }
    public DbSet<Book> Books { get; set; }
}

sealed class AuthorsClub
{
    public int Id { get; set; }
    public string? Name { get; set; }
}
sealed class Author  
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public int AuthorsClubId { get; set; }
    public AuthorsClub? AuthorsClub { get; set; }
}

sealed class Book
{
    public int Id { get; set; }
    public string? Title { get; set; }
    public int AuthorId { get; set; }
    public Author? Author { get; set; }
}
Setup
await using (MyDbContext dbContext = new())
{
    await dbContext.Database.EnsureDeletedAsync();
    await dbContext.Database.EnsureCreatedAsync();

    AuthorsClub authorsClubSouth = new()
    {
        Name = "AC South"
    };
    Author authorOfTheYear2022 = new()
    {
        Name = "Author of the year 2022",
        AuthorsClub = authorsClubSouth
    };
    Book book = new()
    {
        Title = "Fancy Book",
        Author = authorOfTheYear2022
    };
    dbContext.Add(authorsClubSouth);
    dbContext.Add(authorOfTheYear2022);
    dbContext.Add(book);
    await dbContext.SaveChangesAsync();
}
await using (MyDbContext dbContext = new())
{
    AuthorsClub authorsClubNorth = new()
    {
        Name = "AC North"
    };
    Author authorOfTheYear2023 = new()
    {
        Name = "Author of the year 2023",
        AuthorsClub = authorsClubNorth
    };
    dbContext.Add(authorsClubNorth);
    dbContext.Add(authorOfTheYear2023);

    Book book = await dbContext
        .Books
        .Include(b => b.Author)
        .SingleAsync();
    Author authorOfTheYear2022 = book.Author!;
    book.Author = authorOfTheYear2023;
    dbContext.Remove(authorOfTheYear2022);

    // The authorsClubSouth should not be touched.

    await dbContext.SaveChangesAsync(); // ❌
        // Microsoft.EntityFrameworkCore.DbUpdateException -> SqlException
        // The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Authors_AuthorsClub_AuthorsClubId".
        // The conflict occurred in database "EfCore_TempKeySample_Sample", table "dbo.AuthorsClub", column 'Id'.
}
Generated SQL
exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [AuthorsClub] ([Name])
OUTPUT INSERTED.[Id]
VALUES (@p0);
INSERT INTO [Authors] ([AuthorsClubId], [Name])
OUTPUT INSERTED.[Id]
VALUES (@p1, @p2);
',N'@p0 nvarchar(4000),@p1 int,@p2 nvarchar(4000)',@p0=N'AC North',@p1=-2147482646,@p2=N'Author of the year 2023'

Include provider and version information

EF Core version: 7.0 RC1
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0 / .NET 7.0
Operating system: Windows 11
IDE: Visual Studio 2022 17.3.5

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions