Ahmed Alsahli Ahmed Alsahli - 5 months ago 49
AngularJS Question

Using SQL instead of Linq to query database and return Json

I am developing an application using ASP.Net MVC and AngularJS. I am not familiar with linq and honestly I don't like it. But I am very familiar with SQL and I can perform complex queries. So, my question is, I want you to look at the below code from my MVC controller:

public JsonResult GetSupervisor()
{
var db = new scaleDBEntities();
return this.Json((from userObj in db.Users
select new
{
supervisorId = userObj.Id,
supervisorfName = userObj.usrFirstName,
supervisorlName = userObj.usrLastName,
})
, JsonRequestBehavior.AllowGet
);
}


How can I change the link query into SQL query?

I believe that I can do something like this:

var blogNames = db.Database.SqlQuery<string>("SELECT Name FROM dbo.Blogs").ToList();


So, if this is right, how can i use in in my return
this.Json()
for my angular?

Answer

Using the example you provided, something like this should work:

return this.Json(new {blogNames});

You're just creating an anonymously-typed object that the JSON serializer can use to produce an object like this:

{
  "blogNames": ["blog one", "blog two"]
}

It'll be more complicated if you're trying to produce more complex results from a more complex query. But, well, that's what an ORM is for. I'd echo Gert Arnold's advice to embrace LINQ, rather than just deciding you don't like it because you're not used to it.