在Resful api的另一个列表中显示一个列表。

在Resful api的另一个列表中显示一个列表。

问题描述:

我对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

首先你需要更新图片类,像这样。

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