Search code examples
c#asp.net-mvc-3stored-procedureslinq-to-entitieslinq-query-syntax

Convert stored procedure to LINQ


I'm using MVC3 and still learning LINQ. I'm having some trouble trying to convert a query to LINQ to Entities. I want to return an Json method

My stored procedure

Create Procedure [dbo].[ResourceReports]
(
    @EmployeeID int
) 
as
begin
    select   p.projectName AS Projects,  count( b.[CreatedByID]) AS Bugs
    from [EmployeeDetails] e inner join [Bugs] b  on e.[EmployeId] = b.[CreatedByID]
    inner join Projects p on b.ProjectId = p.ProjectId
    where e.[EmployeId] = @EmployeeID   
    group by P.projectName
end 

What I have is a few tables, I started writing this out in LINQ but I'm not sure how to properly return the correct type or cast this.

My controller

public JsonResult Getchart()
{
    var Bug = db.Bugs.ToList<Bug>();
    var EmployeDetails = db.EmployeeDetails.ToList<EmployeeDetail>();
    var projects = db.Projects.ToList<Project>();

    var result = (from e in EmployeDetails 
                  join b in Bug on e.EmployeId equals b.CreatedByID
                  join p in projects on b.ProjectId equals p.ProjectId
                  where e.EmployeId = @EmployeId
                  group p.projectName
                  select new (p.projectName as Project ,count(b.CreatedByID) as Bug)).Take(50);

    return Json(result,JsonRequestBehavior.AllowGet);
}

How will I pass the parameter to for the query, want the data to be returned in json format.


Solution

  • public JsonResult GetChart()
                {
                    //int employeeId
                  var Bug = db.Bugs.ToList<Bug>();
                  var EmployeDetails = db.EmployeeDetails.ToList<EmployeeDetail>();
                  var projects = db.Projects.ToList<Project>();
    
                  var query = (from e in EmployeDetails
                               join b in Bug on e.EmployeId equals b.CreatedByID
                               join p in projects on b.ProjectId equals p.ProjectId
                               where e.EmployeId == 1
                               group new { p, b } by new
                               {
                                   p.projectName
                               } into g
                               select new ChartModel
                               {
                                   ProjectName = g.Key.projectName,                     
    
                                   bug = g.Count()
                               }).ToList();
                  return Json(query, JsonRequestBehavior.AllowGet);
    }
    

    i Got ...