Yes, we can use scaffold-DbContext with view.
using scaffold-DbContext for database view (myview). I executed below scaffold-DbContext query.
Scaffold-DbContext "Data Source=my_server,1433;Initial Catalog=my_database;User Id=my_user;Password=my_password;" Microsoft.EntityFrameworkCore.SqlServer -o Entities -Context ContextName -t myview -f
Once you execute then you will get entity class and contextfile.
Code in entity class (myview.cs)
////// Fetching data
public partial class myview
{
public Guid property_1 { get; set; }
}
Code in dbcontect file (ContextName.cs)
public partial class ContextName : DbContext
{
public virtual DbSet<myview> myview { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<myview>(entity =>
{
entity.HasNoKey();
entity.ToView("myview", "ExtIntDWFS");
////// other property configuration.
}
}
}
Code in controller to fetch view data
////// Fetching data
public async Task<myview> GetView(Base @base)
{
myview obj = new myview();
using (ContextName context = new ContextName())
{
obj = await context.myview.Select(s => new myview
{
property_1 = s.property_1,
}).FirstOrDefaultAsync();
}
return obj;
}
Above code is working for me successfully.