Get a table data from database using WebApi & Entity Framework 6.XX

i made a Entity Data Model From Database Table Like this. enter image description here

Then add 4 line of codes in WebApiConfig.cs to get json data from response.

var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.Remove(config.Formatters.XmlFormatter);

Then i created a Controller (Web API 2 controller with read/Write action) named importController.

then i added this codes to add and retrieve data from database. but not working.

    CodeXenETSEntities db = new CodeXenETSEntities();  

    [HttpPost]
    [ActionName("pushlocation")]
    // POST: api/pushlocation  
    public HttpResponseMessage pushlocation( int userid,decimal longitude, decimal latitude , TimeSpan time )
    {
        user_locations ulog = new user_locations();
        ulog.user_id = userid;
        ulog.lon = longitude;
        ulog.lat = latitude;
        ulog.time = time;
        db.user_locations.Add(ulog);
        db.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.Accepted, "Successfully Created");
    }


    [HttpGet]
    [ActionName("pulllocation")]
    // GET: api/pulllocation/5  
    public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time)
    {

        db.user_locations.ToList();
        return Request.CreateResponse(HttpStatusCode.Accepted, "Success");
    }

this is the output : enter image description here

Database Data :

enter image description here

Upvotes: 2

Views: 2885

Answers (1)

Asif Uddin
Asif Uddin

Reputation: 36

3 things:

1) In WebApiConfig.cs use routeTemplate: "api/{controller}/{action}/{id}"

2) In importController change public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time) to public HttpResponseMessage pulllocation()

3) In Browser address bar use http://localhost:57715/api/{controller name}/pulllocation. in your case http://localhost:57715/api/import/pulllocation

I hope this will solve

Upvotes: 1

Related Questions