Search code examples
c#linqsql-to-linq-conversion

Cannot convert implicity type Syste.Linq.IQueryable<<anonymys type int>> to


I have this SQL query:

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

Write it in LINQ syntax:

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;
   }          
}

And C# return error :

enter image description here

Where is the problem?


Solution

  • result is an enumerable of an anonymous type, not a single int. Instead you need to return a single value. Since you need the votes for a single project, you need to tell the function which project by passing in the ID:

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

    If you need votes for all projects, you need to change the return type to a concrete class, for example:

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

    And your method becomes:

    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();
       }          
    }