无法转换隐含类型Syste.Linq.IQueryable&lt; <anonymys type =“”int =“”>&gt;至

时间:2018-04-09 09:20:17

标签: c# linq sql-to-linq-conversion

我有这个SQL查询:

SELECT project_id,count(project_id) as vote_count 
from Votes 
group by project_id;

用LINQ语法编写:

public int GetCountOfVotes()
{
    using (var db = new SafetyFundDbContext(Options))
    {

        var result = db.Votes
            .GroupBy(vote => vote.ProjectId)
            .Select(group => new
            {
                ProjectID = group.Key,
                Count = group.Count()
            });

        return result;
   }          
}

而C#返回错误:

enter image description here

问题出在哪里?

1 个答案:

答案 0 :(得分:2)

result是匿名类型的可枚举,而不是单个int。相反,您需要返回单个值。由于您需要对单个项目进行投票,因此您需要通过传递ID来告诉函数哪个项目:

public int GetCountOfVotes(int projectId)
{
    using (var db = new SafetyFundDbContext(Options))
    {
        return db.Votes
            .Where(vote => vote.ProjectId == projectId)
            .Count();    
   }          
}

如果您需要对所有项目进行投票,则需要将返回类型更改为具体类,例如:

public class ProjectVotes
{
    public int ProjectID { get; set; }
    public int Votes { get; set; }
}

你的方法变成了:

public IEnumerable<ProjectVotes> GetCountOfVotes()
{
    using (var db = new SafetyFundDbContext(Options))
    {
        return db.Votes
            .GroupBy(vote => vote.ProjectId)
            .Select(group => new ProjectVotes
            {
                ProjectID = group.Key,
                Votes = group.Count()
            })
            .ToList();
   }          
}