rak*_*los 3 .net c# linq-to-sql
嗨我根据他们收到的已经提交的帖子,他们提交的活动以及已收到积分的评论收到的用户积分来计算用户积分 -
public int GetUserPoints(string userName)
{
int? postPoints = db.Posts.Where(p => p.Aspnet_User.UserName == userName).Sum(b => (int?)b.UpVotes);
int? eventPoints = db.Events.Where(p => p.Aspnet_User.UserName == userName).Sum(b => (int?)b.UpVotes);
int? commentPoints = db.Comments.Where(p => p.Aspnet_User.UserName == userName).Sum(c => (int?)c.UpVotes - (int?)c.DownVotes);
return (postPoints.HasValue ? postPoints.Value : 0) + (eventPoints.HasValue ? eventPoints.Value : 0) + (commentPoints.HasValue ? commentPoints.Value / 5 : 0);
}
Run Code Online (Sandbox Code Playgroud)
我正在进行3次单独的db调用来实现这一点.我可以一个人做吗?
如果您确实只需要一次调用并仍然使用LINQ to SQL来构建查询,则可以使用:
var sum = (from p in db.Posts where p.Aspnet_User.UserName == userName select p.UpVotes).Concat
(from e in db.Events where e.Aspnet_User.UserName == userName select e.UpVotes).Concat
(from c in db.Comments where c.Aspnet_User.UserName == userName select (c.UpVotes - c.DownVotes)).Sum()
Run Code Online (Sandbox Code Playgroud)