未映射的值未正确返回

时间:2019-11-30 08:32:10

标签: sql-server asp.net-core asp.net-web-api

我正在编写一个ASP .NET Core Web API项目,并且在我的模型中有一个未映射的道具的问题

这是我的模特

public class Category
    {
        [Key]
        public SqlHierarchyId NodeId { get; set; }
        [Required, MaxLength(200)]
        public string Name { get; set; }
        [Required]
        public int CategoryId { get; set; }
        [NotMapped]
        public int ChildCount { get; set; }
    }

和过程

ALTER PROC [dbo].[GetCategoryChild](@categoryId int)
AS   
BEGIN  
    DECLARE @CurrentNode hierarchyid  
    SELECT @CurrentNode = NodeId FROM Categories
    WHERE CategoryId = @categoryId

SELECT *
,(select count(*) as cc from Categories where NodeId.GetAncestor(1) = ht.NodeId) as ChildCount
    FROM Categories as ht
    WHERE NodeId.GetAncestor(1) = @CurrentNode
END ;  

当我在SQL Server中执行过程时返回预期结果

NodeId    Name     CategoryId     ChildCount
------------------------------------------------
0x58      Books        19             2
0x8C    Computers      25             1

但是当我在Controller中调用它时,所有ChildCounts均为0

NodeId    Name     CategoryId     ChildCount
------------------------------------------------
0x58      Books        19             0
0x8C    Computers      25             0

这是我的控制器

[HttpGet, Route("getChild/{categoryId}")]
        public IEnumerable<Category> GetChild(int categoryId)
        {
            var childs = _db.Categories.
                FromSql($"GetCategoryChild {categoryId}").ToList();
            return childs;
        }

2 个答案:

答案 0 :(得分:0)

构建一个sql命令,并将categoryId变量添加为sqlcommand参数。这就是应该从应用程序代码中调用存储过程的方式。

答案 1 :(得分:0)

您可以从ChildCount模型中删除Category属性,并创建视图模型CategoryViewModel并将结果从存储过程映射到该视图模型:

var param  = new SqlParameter("@categoryId", categoryId);
var result = dbContext.Database
                      .SqlQuery<CategoryViewModel>("dbo.GetCategoryChild @categoryId",param).ToList();

请参阅此链接: Execute stored procedure in entity Framework Core without expecting map to dbset