Efcore: SQL Server Views support

Created on 20 Sep 2017  路  5Comments  路  Source: dotnet/efcore

In order to have entities generated for my SQL Server database views I have to:

  1. create table from view: select top 0 * into dbo.ItemsView2 from dbo.ItemsView
  2. create table PK: alter table dbo.ItemsView2 add constraint PK_ItemsView2 primary key nonclustered (ItemId)
  3. execute: Scaffold-DbContext ...
  4. rename generated classes/properties: ItemsView2 -> ItemsView
  5. drop SQL Server table: drop table dbo.ItemsView2
    The question: is there a better way? Am I missing something?
closed-duplicate closed-question

Most helpful comment

@smitpatel I do not see the point, tables can have missing PKs as well.
Views are mainly used as read-only so why require PK at all?
I would make it simple: no PK -> entity is read-only. No special base classes for views please!
That is, unless you are afraid that such error-proneness will lower perceived product quality but making it unnecessarily complicated does not do serve well either.

All 5 comments

Duplicate of #1679
The main issue is PK for a view, which may not be defined. Hence we cannot scaffold entity type for it always. So on the cautious side, we don't process views.
Once #9290 gets implemented, then perhaps the scaffolding tool can generate ViewType rather than EntityType for views, which can easily be user-edited.

Till then the approach you mentioned is the way to get scaffolding to generate entity type for views.

@smitpatel I do not see the point, tables can have missing PKs as well.
Views are mainly used as read-only so why require PK at all?
I would make it simple: no PK -> entity is read-only. No special base classes for views please!
That is, unless you are afraid that such error-proneness will lower perceived product quality but making it unnecessarily complicated does not do serve well either.

When I follow the advice of the thread starter to use tables to force the scaffolding wizard to generate the entity classes, I found that choosing a name beginning with double underscores like "__Customer" for the "template table" leads to correctly labeled Entityname "Customer", all you have to change is the referenced table name, which in this case can be done by cutting all "__"

It's 2019. Is there still no way for SQL Server Views to be generated? If this is the case, it would be a major setback for our plans to start using ASP.NET Core

@Ljupco7 I am not sure what you are asking, but the functionality this issue was originally asking for is available in EF Core 3.0 preview 6: https://github.com/aspnet/EntityFrameworkCore/issues/1679.

Was this page helpful?
0 / 5 - 0 ratings