用存储过程填充ViewModel

时间:2019-07-25 16:22:33

标签: c# asp.net asp.net-core

我在Sql Server中创建了这个Stored Procedure

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[usp_GetUsrsofRole] (@RoleId int)
AS
;WITH CTE_UsersInRole AS
(
    SELECT 
     U.Id AS [UserId], U.Name AS [UserName] , U.Family AS [UserFamily] , R.Id AS[RoleID],R.Name AS [RoleName]
    FROM AspNetUserRoles AU 
    INNER JOIN AspNetRoles R ON R.Id=AU.RoleId
    INNER JOIN AspNetUsers U ON U.ID=AU.UserId
)
SELECT
     C.RoleID,C.RoleName,C.UserFamily,C.UserId,C.UserName
FROM CTE_UsersInRole C
    WHERE C.RoleID=@RoleId
GO

这是我的视图模型:

public class UserInRoleVM
{
    public string UserName { get; set; }
    public string UserFamily { get; set; }
    public string RoleName { get; set; }
    public int RoleId { get; set; }
    public int UserId { get; set; }

}

现在我需要在ASP Core中用以下代码填充视图模型:

public IEnumerable<UserInRoleVM> GetUserOfRole(int id)
{
    List<UserInRoleVM> users = new List<UserInRoleVM>();
    users = TableAsNoTracking.FromSql("EXEC usp_GetUsrsofRole @p0", id).ToList();
    return users;
}

但是它给了我这个错误:

  

严重性代码描述项目文件行抑制状态   错误CS0029无法隐式转换类型   'System.Collections.Generic.List'   至   'System.Collections.Generic.List'FisziShimi.Services E:\ MyProject \ Farshid \ Backend \ FisziShimi \ FisziShimi.Services \ Services \ UserRoleService.cs 26有效

我该如何解决这个问题?

更新

 public DbSet<TEntity> Entities { get; }
 public virtual IQueryable<TEntity> Table => Entities;
 public virtual IQueryable<TEntity> TableAsNoTracking => Entities.AsNoTracking();

1 个答案:

答案 0 :(得分:5)

您可以执行以下操作。使用上下文和表示视图模型的模型,您可以像这样从存储过程中提取数据。

else

不确定是否重要,但是在存储过程中,确定其RoleID,在模型中,确定其RoleId。不确定是否有所作为。