Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaffold-DbContext Stored Procedures only in EF Core

I have always used code-first with EF Core, Now I need to use Database-First. There are lots of questions, documents, and tutorials about this, teaching how to scaffold a database,

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

However, my only requirement here is missing in all of them. I need to scaffold only a few stored procedures and views, but all these documents and question say is about how to include tables.

I was going to scaffold including everything and then delete unwanted ones manually, but it doesn't seem to be the right choice.

like image 494
Ashkan Mobayen Khiabani Avatar asked Jan 26 '23 12:01

Ashkan Mobayen Khiabani


2 Answers

Use EF Core Power Tools, it allows you to select what to scaffold, and saves your selection.

like image 133
ErikEJ Avatar answered Jan 28 '23 13:01

ErikEJ


It is possible to call a raw SQL using ExecuteSqlCommand. So code to call stored procedure would be look like that:

context.Database.ExecuteSqlCommand("YourStoredProcedure @p0, @p1", 
    parameters: new[] { "Joseph", "Gates" });

UPDATE:

As msdn says about how to get rows from stored procedures:

Raw SQL queries can be used to execute a stored procedure.

var user = "johndoe";

var blogs = context.Blogs
    .FromSqlRaw("EXECUTE dbo.GetMostPopularBlogsForUser {0}", user)
    .ToList();

The following example uses a raw SQL query that selects from a Table-Valued Function (TVF), then disables change tracking with the call to AsNoTracking:

var searchTerm = ".NET";

var blogs = context.Blogs
    .FromSqlInterpolated($"SELECT * FROM dbo.SearchBlogs({searchTerm})")
    .AsNoTracking()
    .ToList();
like image 37
StepUp Avatar answered Jan 28 '23 13:01

StepUp