我目前正在使用Entity Framework 6构建一个web api 2 API。所有这些都很顺利,因为很多api调用只是直接到单个表并将对象作为JSON返回。
现在我的头痛是尝试从各种模型构建单个对象。我首先使用Code。
我想要返回的对象的简化版本是
{ Name : Brand.Name, CategoryScores : [{CategoryId : 'x', Score : 'x'}]}
这些是我目前的型号
[Table("Brands")]
public class BrandModel
{
[Key]
public string BrandId { get; set; }
public string BrandName { get; set; }
}
[Table("CategoryScores")]
public class CategoryScoresModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string BrandId { get; set; }
public string TraqCategoryScore { get; set; }}
public class TraqIndexDTO
{
public string BrandName { get; set; }
public IEnumerable<CategoryScoresDTO> CategoryScores { get; set; }
}
public class CategoryScoresDTO
{
public string CategoryId { get; set; }
public string TraqCategoryScore { get; set; }
}
控制器此处的逻辑将在其工作后移出
private AuthContext db = new AuthContext();
public IHttpActionResult Get()
{
//var results = this.repository.SelectAll();
return Ok(GetTraqIndex());
}
public IEnumerable<TraqIndexDTO> GetTraqIndex()
{
var traqIndex = from b in db.Brand
select new TraqIndexDTO()
{
BrandName = b.BrandName,
CategoryScores = getCatgoryScoresByBrandId(b.BrandId)
};
return traqIndex;
}
public IEnumerable<CategoryScoresModelDTO>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;
}
目前我收到此错误“getCategoryScoresByBrandId(System.String)”方法,并且此方法无法转换为商店表达式。“”
非常感谢任何帮助和指导或良好的示例
谢谢Rob
答案 0 :(得分:1)
修改GetTraqIndex:
public IEnumerable<TraqIndexDTO> GetTraqIndex()
{
var traqIndex = db.Brand.ToList().Select(b => new TraqIndexDTO()
{
BrandName = b.BrandName,
CategoryScores = getCatgoryScoresByBrandId(b.BrandId).ToList()
}).ToList();
return traqIndex;
}