2017-08-25 150 views
0

我對restful api返回了一張圖片列表和一個評論列表,但我不能看到評論列表,我的服務只是返回一個空列表。在Resful api的另一個列表中顯示一個列表。

這是我的GET

api/getjoin/{id:int} 

{ 
    "idPicture": 1, 
    "iduser": 15, 
    "picture": "adress image", 
    "comments": [], 
    "likes": [], 
    "users": null 
    }, 

我想展示我的意見陣列和我喜歡的返還金額。像這樣

{ 
    "idPicture": 1, 
    "iduser": 15, 
    "picture": "adress image", 
    "comments": { 
        "idcomment":1, 
        "comment": bla bla bla; 
       }, 
       { 
        "idcomment":2, 
        "comment": bla bla bla; 
       }, 
       { 
        "idcomment":3, 
        "comment": bla bla bla; 
       }, 

    "likes": { 
        "amount":3; 
       }, 
    "users": null 
    }, 

這是在C#

// GET api/getallpictures by user 
     [HttpGet] 
     [Route("api/getallpictures/{id:int}")] 
     public List<pictures> Getallpictures(int id) 
     { 
      List<pictures> pictureList = new List<pictures>(); 
      List<comments> comemnts = new List<comments>(); 
      List<likes> listlikes = new List<likes>(); 
      var pic = from pictures in dc.pictures 
         where pictures.iduser == id 
         select pictures; 
      foreach (var item in pic) 
      { 
       pictures pc = new pictures(); 
       pc.iduser = item.iduser; 
       pc.idPicture = item.idPicture; 
       pc.picture = item.picture; 
       pictureList.Add(pc); 

      }; 
      return pictureList; 

     } 

我聯繫類這是我的模型類

public class pictures { 
         public int? idPicture { get; set; } 
         public string iduser { get; set; } 
         public string picture { get; set; } 
        } 

public class comments { 
         public int? idcomments { get; set; } 
         public string idPicture { get; set; } 
         public string comment { get; set; } 
         } 
public class likes { 
        public int? idlikes { get; set; } 
        public string idPicture { get; set; } 
        public string amount { get; set; } 
        } 
+0

你想看到評論列表中的圖片作爲迴應,但你的圖片類沒有評論列表。看到問題了嗎? – Reniuz

回答

0

首先你需要更新圖片類,像這樣。

public class pictures 
    { 
     public int? idPicture { get; set; } 
     public string iduser { get; set; } 
     public string picture { get; set; } 
     public List<comments> comments { get; set; } 
     public List<likes> likes { get; set; } 
    } 

現在圖片類與評論和喜歡關係。 現在在你的foreach循環,你可以做,例如

 foreach (var item in pictureList) 
     { 
      pictures pc = new pictures(); 
      //... 

      pc.comments = new List<comments>(); 
      //linq to get comments here 
      pc.comments.Add(new comments()); 

      pc.likes = new List<likes>(); 
      //linq to get likes 
      pc.likes.Add(new likes()); 

      pictureList.Add(pc); 
     }; 

將數據添加到對象以下。

+0

工作正常..非常感謝。 – john

相關問題