[英]Scaffold-DbContext Stored Procedures only in EF Core
I have always used code-first with EF Core, Now I need to use Database-First.我一直在 EF Core 中使用代码优先,现在我需要使用数据库优先。 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.我打算搭建包含所有内容的脚手架,然后手动删除不需要的内容,但这似乎不是正确的选择。
It is possible to call a raw SQL using ExecuteSqlCommand
.可以使用
ExecuteSqlCommand
调用原始 SQL。 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:正如 msdn 所说的如何从存储过程中获取行:
Raw SQL queries can be used to execute a stored procedure.
原始 SQL 查询可用于执行存储过程。
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:
以下示例使用从表值函数 (TVF) 中进行选择的原始 SQL 查询,然后通过调用 AsNoTracking 禁用更改跟踪:
var searchTerm = ".NET";
var blogs = context.Blogs
.FromSqlInterpolated($"SELECT * FROM dbo.SearchBlogs({searchTerm})")
.AsNoTracking()
.ToList();
使用 EF Core Power Tools,它允许您选择要搭建的支架,并保存您的选择。
Just in case someone landed here looking to execute stored procedure in MySQL database from EntityFramework Core, the following code should work.以防万一有人来到这里希望从 EntityFramework Core 执行 MySQL 数据库中的存储过程,下面的代码应该可以工作。
var blogTagId = 1;
var tags = await _dbContext.BlogTags.FromSqlRaw("CALL SP_GetBlogTags({0})", blogTagId).ToListAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.