In EF Core 10, how do you map a database view without a primary key, and what can a keyless entity type not do?
answer
- [Keyless] or HasNoKey()
- ToView names the database object
- never tracked, never saved
- migrations do not create the view
- no navigations pointing at it
basics
~20 sDeclare the class as a keyless entity type with [Keyless] or HasNoKey(), map it with ToView("device_daily_stats"), and expose a DbSet to query it. EF never tracks, inserts, updates or deletes it, and migrations do not create the view.
solid answer
~40 sA keyless entity type is configured with the `[Keyless]` attribute or `modelBuilder.Entity<DeviceDailyStat>().HasNoKey()`, and `ToView("device_daily_stats")` tells EF which database object to read. I then query it through a `DbSet<DeviceDailyStat>` with normal LINQ, including filters, ordering and paging. Limits: it can never be tracked, so it is never inserted, updated or deleted through `SaveChanges`; it cannot be the principal of a relationship, and regular entities cannot have navigations to it, though it may reference regular entities; it is never discovered by convention. Because `ToView` marks the object as a view, migrations do not create it — I add the `CREATE VIEW` myself, usually as raw SQL in a migration. `ToSqlQuery` maps the type to a SQL query defined in the model instead of a named view.
code
csharp · 6 linesmodelBuilder.Entity<DeviceHealthRow>()
.HasNoKey()
.ToSqlQuery("""
SELECT "DeviceId", max("RecordedAt") AS "LastSeen"
FROM "SensorReadings" GROUP BY "DeviceId"
""");go deeper
Know that a view without a key is mapped with [Keyless] or HasNoKey() plus ToView, and that it is read-only for EF.
Explain the navigation limits, why results are never tracked, and why migrations leave the view to you.
Choose between keyless types, ToSqlQuery and SqlQuery<T> for reporting, and manage view definitions alongside migrations.
Decide how much reporting logic lives in database views versus application queries, and who owns their evolution.
## When a keyless entity type fits The IoT platform's database has a view `device_daily_stats` that aggregates readings per device and day. It has no primary key, and many dashboards query it with different filters. Mapping it as a **keyless entity type** makes it a normal LINQ query root. ## Configuration ```csharp [Keyless] public class DeviceDailyStat { public int DeviceId { get; set; } public DateOnly Day { get; set; } public double AvgValue { get; set; } public int Samples { get; set; } public Device Device { get; set; } = null!; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<DeviceDailyStat>() .ToView("device_daily_stats") .HasOne(s => s.Device).WithMany().HasForeignKey(s => s.DeviceId); } public DbSet<DeviceDailyStat> DeviceDailyStats => Set<DeviceDailyStat>(); ``` - `[Keyless]` (from `Microsoft.EntityFrameworkCore`) or the fluent `HasNoKey()` declares the type keyless; one of the two is required. - `ToView` names the database object. From EF's point of view it is read-only, whether it is really a view or a table. - A reference navigation **to a regular entity**, like `Device`, is allowed. Querying is ordinary LINQ: ```csharp var lastWeek = await db.DeviceDailyStats .Where(s => s.Day >= weekAgo && s.AvgValue > 70) .OrderBy(s => s.DeviceId) .ToListAsync(ct); ``` ## What a keyless entity type cannot do 1. **No tracking.** Results are never tracked, and `Add`, `Update` or `Remove` on an instance throws an `InvalidOperationException` because only entity types with a primary key may be tracked. To change the underlying data, write to the base tables. 2. **No key**, by definition, and identity resolution does not apply. 3. **Limited navigations.** It can never be the principal end of a relationship; regular entities cannot have navigations to it; it may only have reference navigations to regular entities; it cannot have navigations to owned types. 4. **Not discovered by convention.** It must be configured explicitly. 5. **Inheritance** must use TPH, and table or entity splitting is not supported. ## Migrations and the view Migrations compare the model's **tables**. An entity mapped with `ToView` is not a table, so `dotnet ef migrations add` does not generate a `CREATE VIEW`. You add the view yourself, typically by writing its SQL into a migration's `Up` method, and keep it in step with the base tables. Mapping a keyless type with `ToTable` instead would make migrations create a table, which is rarely what you want for a view. ## Testing and providers The in-memory provider cannot execute a view definition. To test code that queries a keyless type mapped with `ToView`, run the test against a real PostgreSQL database where a migration has created the view, or, if you must use the in-memory provider, map the type to an in-memory query for tests only. Either way, the read-only nature of the type is enforced by EF in every provider. ## Other ways to get the same rows | Approach | Use when | |---|---| | Keyless type + `ToView` | a database view queried from many places | | Keyless type + `ToSqlQuery` | a fixed SQL query that you want to own in the model rather than in the database | | `Database.SqlQuery<T>` with an unmapped type | a one-off report; nothing added to the model | | `FromSql` on the keyless `DbSet` | a parameterized variant of the same shape | `FromSql` works on keyless `DbSet`s too, so you can feed the same type from a function or an ad hoc statement when the view is not enough.
- Why does dotnet ef migrations add not create the device_daily_stats view?Migrations diff the model's tables, and an entity type mapped with `ToView` is treated as a view, not a table. EF assumes the view already exists. Create it yourself, usually as raw SQL in a migration's `Up` method with a matching drop in `Down`.
- Can a Device entity have an ICollection<DeviceDailyStat> navigation?No. Regular entities cannot have navigations to keyless entity types, and a keyless type can never be the principal of a relationship. The keyless type may point to `Device` with a reference navigation, so query from `DeviceDailyStats` and filter by `DeviceId`.
- Keyless entity types can be inserted if you call SaveChanges.
- EF discovers keyless types by convention from DbSet properties alone.
- Migrations generate CREATE VIEW for anything mapped with ToView.
- A keyless type can be the principal end of a relationship.