ASP MVC API Controller结合了clases结果

时间:2013-11-03 22:36:04

标签: c# asp.net asp.net-mvc asp.net-mvc-4

在ASP MVC Api上我有树命名函数来检索数据,但我想将它们组合到一个请求StylesAll:{},这里是代码。

[ActionName("Styles")]
public IEnumerable<StyleDTO> GetStyles()
{
    return from s in db.styles
           select new StyleDTO() { Name = s.Name, StyleId = s.StyleId };

}


[ActionName("Labels")]
public IEnumerable<LabelDTO> GetLabels()
{
    return from l in db.Labels
           select new LabelDTO() { Name = l.Name, LabelId = l.LabelId , image = l.image};
}

[ActionName("Commodity")]
public IEnumerable<CommodityDTO> GetCommodity()
{
    return from c in db.Commodities
           select new CommodityDTO() { CommodityId = c.CommodityId, CreateDate = c.CreateDate, Name = c.Name, Varieties = ( from v in c.Varieties select new VarietyDTO() 
           {
                CommodityId = v.CommodityId, Name = v.Name, VarietyId = v.VarietyId
           }) };
}

1 个答案:

答案 0 :(得分:3)

创建一个ViewModel以包含所有数据,然后创建函数以填充ViewModel并将其返回。

查看模型

public class AllStyles
{
    public IEnumerable<StyleDTO> Commodities {get;set;}
    public IEnumerable<LabelDTO> Labels {get;set;}
    public IEnumerable<CommodityDTO> Styles {get;set;}
}

API操作方法

[ActionName("StylesAll")]
public AllStyles GetAllStyles()
{
    return new AllStyles{
        Styles = from s in db.styles 
                 select new StyleDTO() { 
                     Name = s.Name, 
                     StyleId = s.StyleId },
        Labels = from l in db.Labels 
                 select new LabelDTO() { 
                     Name = l.Name, 
                     LabelId = l.LabelId , 
                     image = l.image},
        Commodities = from c in db.Commodities 
                      select new CommodityDTO() { 
                          CommodityId = c.CommodityId, 
                          CreateDate = c.CreateDate, 
                          Name = c.Name, 
                          Varieties = ( from v in c.Varieties 
                                        select new VarietyDTO() {
                                            CommodityId = v.CommodityId, 
                                            Name = v.Name, 
                                            VarietyId = v.VarietyId})}
    };
}