首页 > 解决方案 > ASP.NET Core:获取存储过程结果到视图模型

问题描述

我有一个名为 TdetailsVM 的视图模型,如下所示:

public class TdetailsVM 
{
    public Tournaments tourney { get; set; }
    public List<Participants> currentlyjoined { get; set; }
}

现在在控制器中,我将锦标赛的 ID 传递给任务:

public async Task<IactionResult> Details(guid id)
{
    var ThisTourney = _context.Tournaments.FirstOrDefaultAsync(m => m.TID == id);

这会将特定锦标赛的值返回到ThisTourney我稍后将其传递给视图模型的位置

我需要类似的东西:

var ThisParticipants = (result "has many rows" from a stored procedure called SP_GetParticipants that needs a parameter =id)

然后我可以将值传递给视图模型,如下所示

TdetailsVM tvm = new TdetailsVM()
                     {
                          tourney = ThisTourney,
                          currentlyjoined = ThisParticipants
                     }

// then I can return the view 
return view(tvm);

传递第一个要求的数据很好,它可以工作,但我怎样才能传递存储过程?

提前谢谢了

标签: asp.net-corestored-proceduresviewmodel

解决方案


如果您使用的是 Entity Framework Core,那么为了调用您的存储过程,您可以使用这行代码。

List<Participants> participants= _context.Participants.FromSql("SP_GetParticipants @ID",id).ToList();

请注意我如何将@ID值传递给方法中的存储过程FromSql 以及如何将结果映射到List<Participants>. 请查看原始 sql以获取更多信息。

在这行代码之后你有你的列表Participants,然后你可以填写你的父 ViewModel。

var result = new TdetailsVM 
        {
            Tourney = thisTourney,
            Currentlyjoined  = Participants
        };

请注意,建议PascalCase在您的类 (ViewModel) 和私有属性中命名您的公共属性camelCase。请查看通用命名约定 以获取更多信息。


推荐阅读