How to write get method to retrieve data from database using LINQ in Web API in MVC 4.0?

Are you new to concepts of GET , PUT, POST , DELETE of WEB-API in MVC 4.0? This code snippet demonstrates GET method behaviour. I have used simple LINQ query for data retrieval. You can extend this code by adding overloading methods for GET.

Description : It is possible to write overload methods for GET with different method signatures.
These GET can be tested by using fiddler which is a web debugging tool.

public HttpResponseMessage GetRequiredData()
db.Configuration.LazyLoadingEnabled = false;
var outputvalues = (from c in db.yourtablename
select c).ToList();
if (outputvalues == null)
return Request.CreateErrorResponse(HttpStatusCode.NotFound , "No Data Found!" );
return Request.CreateResponse(HttpStatusCode.OK, outputvalues, new System.Net.Http.Headers.MediaTypeHeaderValue("application/Json"));

What is LazyLoadingEnabled?
db.Configuration.LazyLoadingEnabled = false; is used when you have parent child relationship in your tables and you want to avoid all data in the carrier.
If LazyLoadingEnabled is false then it won't carry child data.
What is HttpStatusCode?
If status returned as "HttpStatusCode.NotFound" then it means data is not found.
If status returned as "HttpStatusCode.OK" then it means success in getting data.
Run and test your application
Deploy your application in IIS and give url in fiddler by selecting GET method in the dropdownbox. On success, you will get response as retrieved data.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: