ASP.NET 核心:将存储过程结果获取到视图模型

ASP.NET Core : get stored procedure results to a view model

我有一个名为 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);

这会将 return 特定锦标赛的价值转化为 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);

为第一个要求传递数据没问题,但我怎样才能传递存储过程?

非常感谢

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

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

Note how I passed @ID value to the stored procedure in FromSql method and how mapped the result to List<Participants>. Please have a look at raw sql for more information.

在这行代码之后你得到了 Participants 的列表,然后你可以填充你的父 ViewModel。

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

Note that it is recommended to use PascalCase for naming your public properties in your class (ViewModel) and camelCase for your private ones. Please take a look at General Naming Conventions for more information.