Is it possible to automatically map a DB view on Entity Framework Core version 2.1? c# entity-framework-core


I found this interesting question on stackoverflow about mapping a view and working with it in EF Core.
According to its answer, with previous EF Core versions wasn't possible to automatically map views.

But what now? According to the Entity Framework 2.1 Roadmap,

An EF Core model can now include query types. Unlike entity types,
query types do not have keys defined on them and cannot be inserted,
deleted or updated (i.e. they are read-only), but they can be returned
directly by queries. Some of the usage scenarios for query types are:

  • Mapping to views without primary keys
  • (...)

So the question is: is it possible to automatically scaffold a db context and map its views (like we do for a normal scaffold-dbcontext with an existing database)? If yes, does anyone know how?

Or the only way is still creating them manually as Sampath Kaliyamurthy said in this answer for a previous EF Core version?

6/14/2018 8:17:27 AM

Popular Answer


I found a workaround which consists in:

  1. Rename the view (e.g. from "MyView", to "My_View")
  2. Create a table from that view with a select * into table from view query, and name it like the view initial name (eg. the table will be named "MyView")
  3. Set in the table a primary Key
  4. Scaffold the DB, so you get all the classes and the correct mapping
  5. Remove from the mapping descriptor the HasKey property
  6. Delete the table from the Database and rename the view with its initial name (so, from "My_View" to "MyView" again)

This will make the view works like a normal scaffolded table, you will get all the correct mappings and everything.
The only difference of course is that you won't be able to insert data in it or editing it.
But it's ok since if you want to work with views, you know this from the beginning!



...since despite of this workaround, I still wonder if there's something more "immediate" and "2.1-native", introduced with ef 2.1 as they said in the roadmap.

So any help and/or answer will be such as appreciate!

2/22/2019 11:25:23 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow