C# 动态特性

C# 动态特性,c#,entity-framework,C#,Entity Framework,我试图构建以下内容 CateogoryScores [ "CatShoes" : 10, "CatDress" : 20 ] Catshoes和CatDress是数据库中的实际值。我需要这个形状,因为我需要能够用javascript编写以下内容。分类分数[猫靴]等 这是我的模型 public class CategoryScoresDTO { public string CategoryId { get; set; } public string TraqCat

我试图构建以下内容

CateogoryScores [
    "CatShoes" : 10,
    "CatDress" : 20
]
Catshoes和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;
    }

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

您应该能够在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);
    }

谢谢你的建议,但最后我需要返回一个Dictionary对象以获得所需的结果

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;
    }

“形状”这个词令人费解。您的意思是要将结果序列化为JSON格式吗?您所说的形状是什么意思?很抱歉,是的,对象将序列化为JSON,它已经这样做了,更多的是让值成为数组的属性//当前JSON CategoryScores:[{CategoryId:ALLCAT,TraqCategoryScore:53.89720374},{CategoryId:CHI0001,TraqCategoryScore:20.04790595}]//通缉Json categoryscore:[ALLCAT:53.89720374,CHI0001:20.04790595]@RobPaddock添加序列化代码。