【问题标题】:Fill ViewModel with Stored Procedure用存储过程填充 ViewModel
【发布时间】:2019-07-27 12:01:51
【问题描述】:

我在 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();

【问题讨论】:

  • @CodeNotFound 是

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


【解决方案1】:

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

List<UserInRoleVM> users = new List<UserInRoleVM>();
using (var context = new DataContext())
{
   SqlParameter Parameter = new SqlParameter("@p0", code);
   users = context.Database.SqlQuery<UserInRoleVM>("exec usp_GetUsrsofRole  @p0", Parameter).ToList();
}
return users;

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

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多