Skip to content

Get an EntityEntry<TEntity> for Shared Entity Types #25354

@zoriya

Description

@zoriya

Get an EntityEntry for Shared Entity Types

Right now, it is impossible to access an EntityEntry (via Context.Entry(obj)) for a SharedEntity and this prevents us from changing states of entries.

(Not really necessary to understand the issue, but I need to access the EntityEntry of the shared entity because I want to set the state of the shared entity to Added while keeping related entities to Unchanged)

Reproducible example

private class TestEntity
{
	public int ID { get; set; }
	public ICollection<TestShared> Shared { get; set; }
}

private class TestShared
{
	public int ID { get; set; }
	public string Property { get; set; }
}

private class SharedEntityContext : DbContext
{
	public DbSet<TestEntity> Entities { get; set; }

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		optionsBuilder.UseSqlite(":memory:");
	}

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		modelBuilder.SharedTypeEntity<TestShared>("EntityShared")
			.HasKey(x => x.ID);
		modelBuilder.SharedTypeEntity<TestShared>("EntityShared")
			.HasOne<TestEntity>()
			.WithMany(x => x.Shared)
			.OnDelete(DeleteBehavior.Cascade);
	}
}

[Fact]
public void SharedEntityEntryTest()
{
	using SharedEntityContext context = new();
	
	TestEntity show = new();
	context.Entry(show); // This does not throw;

	TestShared id = new();
	context.Entry(id); // This throws.
}

Stack Traces

System.InvalidOperationException
The entity type 'TestShared' was not found. Ensure that the entity type has been added to the model.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateEntry(Object entity)
   at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity)
   at Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity entity)
   at Kyoo.Tests.Database.GlobalTests.SharedEntityEntryTest() in /home/anonymus-raccoon/Projects/Kyoo/Kyoo/Kyoo.Tests/Database/SpecificTests/SanityTests.cs:line 82

Include provider and version information

EF Core version: 5.0.8
Database provider: Microsoft.EntityFrameworkCore.Sqlite 5.0.8 & Npgsql.EntityFrameworkCore.PostgreSQL 5.0.7
Target framework: NET 5.0
Operating system: Linux
IDE: Rider

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions