How can I use database Views in a scaffolded DbContext with Entity Framework Core 1.0 (EF7)

entity-framework-core view


Unfortunately Entity Framework Core 1.0 (formerly Entity Framework 7) does not yet support Views, and I'm trying to 'fake' it using a table.

However the scaffolding dotnet dbcontext ef scaffold command doesn't currently recognize or generate views, and I want a single DbContext which allows querying a view and updating of tables. Is there a way to do this?

This is the command I use to scaffold the DbContext:

dotnet ef dbcontext scaffold -c MyStoreContext -o Model "Data Source=(local);Initial Catalog=DBNAME;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer --force

(This puts all my model classes in a Model directory, and forces them to be overwritten.)

Note: The reason I actually want to use a View is for GROUP BY logic, which isn't supported either in EF Core 1.0

5/27/2016 2:33:15 AM

Popular Answer

For me, my view was in a different schema, so I had to alter an attribute on the model class:

using System.ComponentModel.DataAnnotations.Schema;

namespace API.DataAccess
    [Table("MyViewName", Schema = "SomeSchema")]
    public class MyViewName

For completeness, the entity code:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    modelBuilder.Entity<MyViewName>(entity =>
        entity.HasKey(e => new { e.SomeColumn }).HasName("PK_FAKEKEY");
            entity.Property(e => e.SomeColumn ).IsRequired();
            entity.Property(e => e.SomeColumn2 );
            entity.Property(e => e.SomeColumn3 );
2/2/2017 9:21:29 PM

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