efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Deleting an attached entity in TPH succeeds even if it is of the wrong type

Open Xriuk opened this issue 1 year ago • 0 comments

Include your code

public DbSet<BlogBase> AllBlogs { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<RssBlog> RssBlogs { get; set; }

public abstract class BlogBase
{
    public int BlogId { get; set; }
}

public class Blog : BlogBase{ }

public class RssBlog : BlogBase{ }

// Populating the db (let's say BlogId will be 1)
db.Add(new RssBlog());
db.SaveChanges();

// Later for performance reasons, after a user request, we attach an entity to be deleted, 
// but the user enters the wrong type
// (this is simplified but it happens dynamically with reflection)
var entity = new Blog{ // Is RssBlog but the user was mistaken
    BlogId = 1
};
db.Attach(entity);
db.Entry(entity).State = EntityState.Deleted;
db.SaveChanges(); // Here it succeeds, but it shouldn't

The generated SQL command looks like this:

DELETE FROM "AllBlogs"
WHERE "BlogId" = 1;
SELECT changes();

When IMO it should include the discriminator for TPH entities like this:

DELETE FROM "AllBlogs"
WHERE "BlogId" = 1 AND "Discriminator" = "Blog";
SELECT changes();

So it would fail as the types do not match.

Include provider and version information

EF Core version: 6.0.14 Database provider: Microsoft.EntityFrameworkCore.Sqlite Target framework: .NET 6.0

Xriuk avatar Feb 13 '24 10:02 Xriuk