Is it possible to automatically map a DB view on Entity Framework Core version 2.1?

大兔子大兔子 提交于 2021-01-23 11:10:38

问题


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:

  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!


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!