c# 动态属性

本文关键字:属性 动态 | 更新日期: 2023-09-27 18:36:04

我正在尝试构建以下内容

CateogoryScores [
    "CatShoes" : 10,
    "CatDress" : 20
]

Catsho 和 CatDress 是数据库中的实际值。我需要这个形状,因为我需要能够用javascript编写以下内容。分类分数["猫鞋"]等

这是我的模型

public class CategoryScoresDTO
{
    public string CategoryId { get; set; }
    public string TraqCategoryScore { get; set; }
}

这是我从表中获取数据的函数

private IEnumerable<CategoryScoresDTO> GetCatgoryScoresByBrandId(string brandId)
    {
        var scores = from s in db.CategoryScoresModel
                     where s.BrandId == brandId
                     select new CategoryScoresDTO()
                     {
                         CategoryId = s.CategoryId,
                         TraqCategoryScore = s.TraqCategoryScore
                     };
        return scores;
    }

显然这不是我想要返回的形状,因为它只是一个列表,而不是我需要的正确形状

c# 动态属性

你应该能够在WebApi控制器中做这样的事情。

private IHttpActionResult GetCatgoryScoresByBrandId(string brandId)
    {
        var scores = from s in db.CategoryScoresModel
                     where s.BrandId == brandId
                     select new CategoryScoresDTO()
                     {
                         CategoryId = s.CategoryId,
                         TraqCategoryScore = s.TraqCategoryScore
                     };
        return Json(scores);
    }

感谢您的建议,但最终我需要返回一个字典对象才能获得所需的结果

private Dictionary<string, string> GetCatgoryScoresByBrandId(string brandId)
    {
        var scores = from s in db.CategoryScoresModel
                     where s.BrandId == brandId
                     select new CategoryScoresDTO()
                     {
                         CategoryId = s.CategoryId,
                         TraqCategoryScore = s.TraqCategoryScore,
                     };
        Dictionary<string, string> categoryScores = new Dictionary<string, string>();
        categoryScores = scores.ToDictionary(x => x.CategoryId, x => x.TraqCategoryScore);

        return categoryScores;
    }