Efcore: Question: HasNoKey and unit testing

Created on 26 Sep 2019  路  6Comments  路  Source: dotnet/efcore

With the move from DbQuery to DbSet and a call to HasNoKey for a view in MVC Core what is the expected pattern for seeding data for unit testing?

If I call the Add method on my DbSet<> object it fails Unable to track an instance of type xxx because it does not have a primary key. Only entity types with primary keys may be tracked.

Which makes sense. So is there a way of getting round this for the inmemory database?

closed-question customer-reported

Most helpful comment

Could someone please post an example of what you mean by "defining query"?

All 6 comments

In order to use keyless entity types in InMemoryDatabase you need to use defining queries to define how to get database for those query roots. Defining query is API which allows you to write linq query to generate database for given entityType based on other entityTypes in the model. It is SQL equivalent of view definition on the database.

Hi there - I can't see how this would work when by view is mapped in my ApplicationDbContext OnModelCreating or can I write code in there conditional on whether I am running the InMemoryDatabase or SQL server? The view is currently defined there as:
```
builder.Entity().HasNoKey();
builder.Entity().ToView("VW_BOOKINGS")
.Property(v => v.BookingId).HasColumnName("BOOKING_ID");

```
My unit tests create an instance of the ApplicationDbContext and pass it to controllers etc. for testing.

@MCFHTAGENTS
C# if (Database.ProviderName == "Microsoft.EntityFrameworkCore.InMemory") { ... } else { ... }

OK - i have the defining query working but, remembering the whole point of this is to seed data into my view for unit testing, have now run into the limitation that I can't use the Include construct for linked tables with defining queries... These are necessary for the SQL implementation of my code and so increasingly move my unit test away from testing the real code.

@MCFHTAGENTS That part would be covered by https://github.com/aspnet/EntityFrameworkCore/issues/17158

Could someone please post an example of what you mean by "defining query"?

Was this page helpful?
0 / 5 - 0 ratings