C# Web API INNER JOIN and RETURN Query value

前端 未结 3 1319
说谎
说谎 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:59

    Hopefully your join works ?!

    If so, you can run your query through EF and get the results like below :

    namespace WebApiJoinData.Controllers
    {
    [RoutePrefix("Api")]
    public class JoinController : ApiController
    {
        DepartmentServicesEntities DSE = new DepartmentServicesEntities();
        [Route("Api")]
    
    
            [HttpGet]
            public object JoinStatement()
            {
                string Msg = String.Empty;
                string sql = String.Format("Select FirstName, LastName, Gender, Salary, E.Department_id, Department_Name from Employee E INNER JOIN Department D on D.department_id = E.department_id");
    
                using (DSE)
                {
                    //proceed the query and return Msg
                    var results = DSE.Database.SqlQuery(sql).ToList();                    
                    Msg = Newtonsoft.Json.JsonConvert.SerializeObject(results);                    
                    return results;
                }
            }
        }
    }
    
    
    

    I would suggest you create a DTO class instead of using object as this will help when you have large amounts of data.

    Another way could be you return the data as json string

    提交回复
    热议问题