With EF Core 5, is it possible to reverse engineer (Scaffold-DbContext) a SQL view as an editable table?

Bruno71 1 Reputation point
2021-12-14T15:39:56.827+00:00

I'm using Entity Framework Core 5 in my "database first" application. I use the 'Scaffold-DbContext' command to re-create the models whenever the database schema changes. It works great.

However, I now have a SQL View that I need to update so that it writes the value back to the underlying table. The view in my application's database is actually referencing a table in another database, or else I would just update the table directly.

Using the Scaffold-DbContext command, it generates the view entity as follows...

modelBuilder.Entity<vwMyViewName>(entity =>
  {
  entity.HasNoKey();
  entity.ToView("vwMyViewName");
...etc...

But I can't update the view because 1) it has no key defined, and 2) it was created as .ToView(). But if I change the generated model to the following...

modelBuilder.Entity<vwMyViewName>(entity =>
  {
  entity.HasKey(e => e.key_field_name);
  entity.ToTable("vwMyViewName");
...etc...

...then it works they way I would like and will update the value in the database when I call context.SaveChanges().

So, is it possible to have EF Core reverse engineer the SQL views as editable tables with keys? Or is there a better way to write changes back to an EF Core keyless entity?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,370 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,239 questions
{count} votes