Reputation: 516
So what this code is supposed to do is work out how many 'likes' a user has and then return that value as the 'UserPhoto.Likes' value. Currently i'm getting the whole 'UserPhoto' model and working out the 'Likes' but not putting the two together like I want it to.
[HttpGet("{userId}/photo/{photoId}")]
public async Task<IQueryable> GetUserPhoto(int userId, int photoId)
{
var photos = _context.UserPhotos.Where(x => x.UserId == userId).Include(p => p.Likers);
var photo = photos.Where(x => x.Id == photoId);
var likes = _repo.CountUserLikes(userId, photoId);
// this line gets the total amount of likes for that photo
var whole = photo.Include(x => x.Likes as likes);
// this line is where I tried to send 'Likes' as 'likes'
return whole;
}
This is what should be returned from this request, just with the correct amount of likes (as you can see there is 1 like there, so likes should say 1, but it says 0. Also there is no error in the line
var likes = _repo.CountUserLikes(userId, photoId);
as this does return the correct amount of likes, I've tested it
[
{
"id": 1,
"photoUrl": "https://scontent-lhr8-1.cdninstagram.com/v/t51.2885-19/s150x150/39810479_537470876724057_5547938285650706432_n.jpg?_nc_ht=scontent-lhr8-1.cdninstagram.com&_nc_ohc=MBSkwH6PVzgAX9iSKsc&oh=39e4f480573fc78cf0afefb8820cdd19&oe=5EB8228C",
"description": "Non deserunt labore sunt ex laboris et adipisicing ullamco officia minim.",
"dateAdded": "0001-01-01T00:00:00",
"isMain": true,
"publicId": null,
"isImage": true,
"mainImage": "https://scontent-lhr8-1.cdninstagram.com/v/t51.2885-19/s150x150/39810479_537470876724057_5547938285650706432_n.jpg?_nc_ht=scontent-lhr8-1.cdninstagram.com&_nc_ohc=MBSkwH6PVzgAX9iSKsc&oh=39e4f480573fc78cf0afefb8820cdd19&oe=5EB8228C",
"userId": 1,
"likers": [
{
"id": 1,
"imageId": 1,
"likerId": 1
}
],
"likes": 0
}
]
Also, in the model, 'Likes' is just an integer value:
public int Likes { get; set; }
Upvotes: 0
Views: 34
Reputation: 1613
As Ryan Thomas said, you can simply declare the Likes property as a read-only property which returns the count of the likers whenever it's accessed:
public int Likes => likers.Count()
This is not a static value, it's a property on each object.
I think the .Include() method is not really clear to you. I would suggest to look it up a bit more here. In reality though, it is used to add more data to the return result from tables that you did not specify in your query, but are connected with your table.
Upvotes: 2