C# Web API INNER JOIN and RETURN Query value

前端 未结 3 1266
说谎
说谎 2021-01-27 02:29

EF Model Image References

I was planned to read data from database and then using INNER JOIN in C# WebApi contr

3条回答
  •  遥遥无期
    2021-01-27 02:53

    As per the Model given above, you should change your query as something like:

    public class JoinController: ApiController
    {
    DepartmentServicesEntities DSE = new DepartmentServicesEntities();
    [Route("Api")]
    
        [HttpGet]
        public object JoinStatement()
        {
            using (DSE)
            {
                var result = (from e in DSE.employee join d 
                in DSE.department on e.department_id equals d.department_id 
                select new {
                FirstName = e.FirstName, 
                LastName = e.LastName, 
                Gender = e.Gender, 
                Salary = Salary, 
                Department_id = e.Department_id, 
                Department_Name = d.Department_Name
                }).ToList();
            // TODO utilize the above result
            }
        }
    }
    

    There is only one issue with the above code as the result will always be an Anonymous Type object. So, it is advisable to use a Data Transfer Object(DTO) whenever you have a case of multi-entity join result for proper mapping.

提交回复
热议问题