Error on initialize a DbSet without key: Unable to track an instance of type 'MyEntity' because it does not have a primary key
Asked Answered
S

2

5

I have a DbContext which has a Dbset without Key. It works in the application, which only queries the table.

public class MyDbContext : DbContext, IMyDbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
    public DbSet<MyEntity> MyEntities { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>().HasNoKey(); // No key
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
    }
}

I create the following test setup classes in the test project (xUnit):

public static class MyDbContextFactory
{
    internal static MyDbContext Create()
    {
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
        var context = new MyDbContext(options);
        context.Database.EnsureCreated();
        context.MyEnities.AddRange(new[] // This line got the error!!!
        {
            new MyEntity { Time = DateTime.Now, Instrument = "R1" },
            new MyEntity { Time = DateTime.Now, Instrument = "R2" },
            new MyEntity { Time = DateTime.Now, Instrument = "R3" },
        });
        context.SaveChanges();
        return context;
    }
}

public class QueryTestFixture : IDisposable
{
    public MyDbContext MyDbContext { get; }
    public IMapper Mapper { get; }

    public QueryTestFixture()
    {
        MyDbContext = MyDbContextFactory.Create();
        var configurationProvider = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<MappingProfile>();
        });
        Mapper = configurationProvider.CreateMapper();
    }

    public void Dispose()
    {
        // ... omitted ...
    }
}

[CollectionDefinition("QueryTests")]
public class QueryCollection : ICollectionFixture<QueryTestFixture> { }

And here is the Test code.

[Collection("QueryTests")]
public class MyTest
{
    private readonly MyDbContext _context;
    private readonly IMapper _mapper;

    public MyTest(QueryTestFixture fixture)
    {
        _context = fixture.MyDbContext;
        _mapper = fixture.Mapper;
    }
}

However, running any test method will get the following error before the tests are actually run. The error occurred on the line context.MyEnities.AddRange(.... above.

 Message: 
    System.AggregateException : One or more errors occurred. (Unable to track an instance of type 'MyEntity' because it does not have a primary key. Only entity types with primary keys may be tracked.) (The following constructor parameters did not have matching fixture data: QueryTestFixture fixture)
    ---- System.InvalidOperationException : Unable to track an instance of type 'MyEntity' because it does not have a primary key. Only entity types with primary keys may be tracked.
    ---- The following constructor parameters did not have matching fixture data: QueryTestFixture fixture
  Stack Trace: 
    ----- Inner Stack Trace #1 (System.InvalidOperationException) -----
    StateManager.GetOrCreateEntry(Object entity)
    DbContext.SetEntityStates(IEnumerable`1 entities, EntityState entityState)
    DbContext.AddRange(IEnumerable`1 entities)
    DbContext.AddRange(Object[] entities)
    InternalDbSet`1.AddRange(TEntity[] entities)
    MyDbContextFactory.Create() line 20
    QueryTestFixture.ctor() line 16
    ----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----
Semiskilled answered 16/12, 2019 at 19:43 Comment(6)
What are you trying to test? Why don't you use a mock of IMyDbContext instead use a concrete instance of MyDbContext?Sarcoma
Have you tried to use AsNoTracking for queries?Bibi
@Semiskilled on the real application DbSet<MyEntity> is mapping a View or a Table?Sarcoma
@LuttiCoelho, it's a view.Semiskilled
@PavelAnikhouski, where to add AsNoTracking? I tried to add it (` context.MyEnities.AsNoTracking();) right before context.MyEnities.AddRange(...)` but it still got the error.Semiskilled
You are using actual DbContext object not the mocked one.Theological
S
4

Until now this is an open issue on Entity Framework: https://github.com/aspnet/EntityFramework.Docs/issues/898

You can not add new entities on a DbQuery or an DbSet with no key. I suggest you to keep track on this issue and for now mock your Context or to use Entity Framework Core Mock to accomplish that.

Sarcoma answered 16/12, 2019 at 20:15 Comment(0)
K
3

Below solution worked for me.

For scenarios #1 and #2 you can add the following line to DbContext module OnModelCreating method: modelBuilder.Entity().HasKey(x => new { x.column_a, x.column_b }); // as many columns as it takes to make records unique.

Detailed info of the query is on tis url.

https://mcmap.net/q/134977/-entity-framework-table-without-primary-key#:~:text=EF%20does%20not%20require%20a,I%20believe%20you%20are%20hosed.

Kathrynkathryne answered 6/4, 2021 at 8:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.