Entity Framework .Net core not adding stored procedure classes

asp.net-core c# entity-framework-core stored-procedures

Question

I am generating Entity Framework classes in a .NET Core application using this command:

Scaffold-DbContext "Server=server name;Database=DB name;user id=user name;password=password;Trusted_Connection=False;Encrypt=True;" 
         Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB 

It is working well and creating models for all the tables and views in the database. But strangely it's not creating models for stored procedures.

Is there anything I am missing in scaffold syntax?

1
0
4/1/2020 4:54:22 PM

Accepted Answer

Entity Framework Core creates entity classes only for tables; stored procedures or views are still not supported.

But there is a Github issue tracking on it that you can find more info: Stored procedure mapping support

How to add stored procedures (like a normal entity) after scaffolding:

  1. Create the output model of your stored procedure:

    public class SampleModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
  2. Add a new DbSet to your context :

    public virtual DbSet<SampleModel> SampleModels { get; set; }
    
  3. Use your model for the output:

    var sampleModels = _context.SampleModels.FromSql($"EXEC ReturnAllSampleModels").ToList();
    

Done.

0
4/1/2020 4:55:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow