C# 计算出值并在调用时推入模型
因此,这段代码要做的是计算出一个用户有多少个“喜欢”,然后将该值作为“UserPhoto.likes”值返回。目前,我正在获取整个“UserPhoto”模型,并计算出“Likes”,但没有像我希望的那样将两者结合起来C# 计算出值并在调用时推入模型,c#,.net,C#,.net,因此,这段代码要做的是计算出一个用户有多少个“喜欢”,然后将该值作为“UserPhoto.likes”值返回。目前,我正在获取整个“UserPhoto”模型,并计算出“Likes”,但没有像我希望的那样将两者结合起来 [HttpGet("{userId}/photo/{photoId}")] public async Task<IQueryable> GetUserPhoto(int userId, int photoId) { var pho
[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;
}
由于这确实返回了正确数量的喜欢,我已经对它进行了测试
[
{
"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
}
]
此外,在模型中,“Likes”只是一个整数值:
public int Likes { get; set; }
正如Ryan Thomas所说,您可以简单地将Likes属性声明为只读属性,每当访问它时,它都会返回likers的计数:
public int Likes=>likers.Count()
这不是静态值,而是每个对象的属性
我认为.Include()方法对您来说不是很清楚。我建议再多查一下。但实际上,它用于向查询中未指定但与表连接的表的返回结果中添加更多数据 正如Ryan Thomas所说,您可以简单地将Likes属性声明为只读属性,每当访问它时,它都会返回likers的计数:
public int Likes=>likers.Count()
这不是静态值,而是每个对象的属性
我认为.Include()方法对您来说不是很清楚。我建议再多查一下。但实际上,它用于向查询中未指定但与表连接的表的返回结果中添加更多数据 你不能做像public int Likes{get=>likers.Count()}这样的事情吗好的,我已经做了,它可以工作了,但是这会为Likes创建一个静态值吗?它需要是动态的,因为喜欢的数量可以增加或减少不,它不会是静态的。每次访问该属性时都会调用Count()方法。您不能像public int Likes{get=>likers.Count()}这样做吗?好的,我已经这样做了,它可以工作,但这会为Likes创建一个静态值吗?它需要是动态的,因为喜欢的数量可以增加或减少不,它不会是静态的。每次访问该属性时都将调用Count()方法。
public int Likes { get; set; }