我有一個Items
表和ItemVotes
表,每個用戶可以放棄投票或向下投票到一個項目和他/她的投票決定由ItemVotes
表中的bool
財產。現在我想要有一個Items
排行榜的清單,爲此,我們需要得到true
票數減去false
票數。LINQ查詢計算投票計數
_ItemsService.GetAll(x => x.ItemVotes //here I have to order by vote)
UPDATE:
項目實體:
public class Items : Entity<int>
{
public int UserId { get; set; }
public DateTime Date { get; set; }
public string Subject { get; set; }
public virtual ICollection<ItemVotes> ItemVotes { get; set; }
}
ItemVotes實體:
public class ItemVotes : Entity<int>
{
public int ItemId { get; set; }
public int UserId { get; set; }
public DateTime Date { get; set; }
public bool TypeVote { get; set; }
public virtual Items Items { get; set; }
public virtual Users Users { get; set; }
}
更新2:
我用吉拉德格林的答案在動作是這樣的:
public ActionResult TopItems()
{
var items = _ItemsService.GetAllQuerable(x => x)
.OrderBy(item => item.ItemsVote.Sum(vote => vote.TypeVote ? 1 : -1));
return View(items);
}
這裏是GetAllQuerable()
功能:
public IEnumerable<T> GetAllQuerable(
Expression<Func<T,
bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = "")
{
return _repository.GetAllQuerable(filter, orderBy, includeProperties);
}
這將有助於展示更廣泛的代碼範圍和你的對象 –
@GiladGreen我已經更新了它。 – mohammad
看到我的回答在 –