Jose
Jose

Reputation: 1067

ASP MVC API Controller combined clases result

on a ASP MVC Api I have tree named functions to retrieve data but I would like to combine them to one request StylesAll:{ }, here is the code.

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

Upvotes: 2

Views: 118

Answers (1)

Tommy
Tommy

Reputation: 39807

Create a ViewModel to contain all of the data, then create the function to populate the ViewModel and return it.

View Model

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

API Action Method

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

Upvotes: 3

Related Questions