问题
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?
回答1:
WORKAROUND SOLUTION:
I found a workaround which consists in:
- Rename the view (e.g. from "MyView", to "My_View")
- 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") - Set in the table a primary Key
- Scaffold the DB, so you get all the classes and the correct mapping
- Remove from the mapping descriptor the
HasKey
property - 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!
But
CONSIDER THIS QUESTION STILL OPENED...
...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!
来源:https://stackoverflow.com/questions/50834648/is-it-possible-to-automatically-map-a-db-view-on-entity-framework-core-version-2