[英]How to return an array/list from an assembly to a stored procedure in SQL Server?
[英]SQL Join Stored Procedure Does Not Return List In Blazor Server
在这里,我有 blazor 服务器应用程序,其中存储过程[dbo].[spGetAllChapter]
返回章节名称列表,class 名称和 SSMS 中的主题名称。
要调用此存储过程[dbo].[spGetAllChapter]
,我使用_dbContext.Database.ExecuteSqlRaw()
。
现在,问题是在调用存储过程时它不返回列表而是显示-1 值,但是在 SSMS 中执行相同的存储过程时返回列表。
下面是我的存储过程
ALTER PROCEDURE [dbo].[spGetAllChapter]
AS
BEGIN
SELECT CH.ChapterId
, CH.ChapterName
, SC.ClassName
, S.SubjectName
FROM [dbo].[Chapter] AS CH
JOIN [dbo].[SchoolClass] AS SC
ON CH.SchoolClassId= SC.SchoolClassId
JOIN [dbo].[Subject] AS S
ON CH.SubjectId = S.SubjectId
END
下面是我如何调用存储过程
public eLearningDBContext _dbContext = new eLearningDBContext();
//getChapterList is -1 instead of returning list from procedure
var getChapterList = _dbContext.Database.ExecuteSqlRaw($"EXEC dbo.spGetAllChapter");
ExecuteSqlRaw的文档说 function:
Executes the given SQL against the database and returns the number of rows affected.
请注意,它不返回数据,而是返回受影响的行数。 也许您正在寻找的是FromSqlRaw
或者,您不需要存储过程来完成您想要的; 您可以简单地在常规 EF 查询中投影所需的列,例如:
_dbContext.Chapters.Select(ch => new
{
ChapterId = ch.ChapterId,
ChapterName = ch.ChapterName,
ClassName = ch.SchoolClass.ClassName,
SubjectName = ch.Subject.SubjectName
}).ToList()
这将为您提供一个包含所需字段的匿名对象列表,但您也可以创建一个命名类型(如ChapterAbstract
或其他东西)并对其进行投影。
如果上下文是首先创建的数据库,您可以通过向导更新 DataModel 以包含存储过程和函数。 然后你可以直接从上下文中调用SP
_dbcontext.spGetAllChapter();
我通过制作这个助手 class 解决了一些问题
public static class SQLHelper
{
public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> function)
{
using (var context = new eLearningDBContext())
{
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = query;
command.CommandType = CommandType.Text;
context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
var entities = new List<T>();
while (result.Read())
{
entities.Add(function(result));
}
return entities;
}
}
}
}
}
var list = SQLHelper.RawSqlQuery($"EXEC dbo.spGetAllChapter",
x => new ChapterVM {
ChapterId = (int)x[0],
ChapterName = (string)x[1],
ClassName = (string)x[2],
SubjectName = (string)x[3]
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.