簡體   English   中英

使用 WebApi & Entity Framework 6.XX 從數據庫中獲取表數據

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

我從數據庫表中制作了一個實體數據模型,就像這樣。 在此處輸入圖片說明

然后在 WebApiConfig.cs 中添加 4 行代碼以從響應中獲取 json 數據。

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

然后我創建了一個名為 importController 的控制器(具有讀/寫操作的 Web API 2 控制器)。

然后我添加了這個代碼來添加和檢索數據庫中的數據。 但不工作。

    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");
    }

這是輸出: 在此處輸入圖片說明

數據庫數據:

在此處輸入圖片說明

3件事:

1)WebApiConfig.cs使用routeTemplate: "api/{controller}/{action}/{id}"

2)importController public HttpResponseMessage pulllocation(int userid, decimal longitude, decimal latitude, TimeSpan time)更改為public HttpResponseMessage pulllocation()

3)在瀏覽器地址欄中使用http://localhost:57715/api/{controller name}/pulllocation 在你的情況下http://localhost:57715/api/import/pulllocation

我希望這會解決

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM