【问题标题】:not mapped value doesn't return correct未映射的值不返回正确
【发布时间】:2019-12-16 21:13:35
【问题描述】:

我正在编写一个 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;
        }

【问题讨论】:

  • 如果您的 sp 返回该键,那么您为什么使用未映射?我的意思是删除该属性并重试
  • @PrashantPimpale 然后它根本不返回 ChildCount

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


【解决方案1】:

构建 sql 命令并将 categoryId 变量添加为 sqlcommand 参数。这就是你应该如何从应用程序代码调用存储过程。

【讨论】:

    【解决方案2】:

    您可以从Category 模型中删除ChildCount 属性,并创建一个视图模型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

    【讨论】:

    • 不能在英文中每个单词都大写,每个单词都用粗体突出显示.....
    猜你喜欢
    • 2022-07-06
    • 2020-08-02
    • 1970-01-01
    • 2019-09-28
    • 2013-09-15
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多