public IHttpActionResult Post(LandTypeViewModel item_viewModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } LandType item = new LandType { Id = item_viewModel.Id, Type=item_viewModel.Type}; //不需指定Timestamp欄位 db.LandTypes.Add(item); try { db.SaveChanges(); } catch (DbEntityValidationException ex) { var entityError = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage); var getFullMessage = string.Join("; ", entityError); var exceptionMessage = string.Concat(ex.Message, "errors are: ", getFullMessage); throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, exceptionMessage)); } return CreatedAtRoute("DefaultApi", new { id = item.Id }, ToLandTypeViewModel(item)); }
public IHttpActionResult Put(int id, LandTypeViewModel item_viewModel) { if (!ModelState.IsValid) return BadRequest(ModelState); if (id != item_viewModel.Id) return BadRequest(); //把資料庫中的那筆資料讀出來 var item_db = db.LandTypes.Find(id); if (item_db == null) { return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, "這筆資料已被刪除!")); } else { try { //不需指定Id item_db.Type = item_viewModel.Type; //Timestamp欄位以如下方式設定 db.Entry(item_db).OriginalValues["Timestamp"] = Convert.FromBase64String(item_viewModel.TimestampString); db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (db.LandTypes.Find(id) == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "這筆資料已被刪除!")); else throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, "這筆資料已被其他人修改!")); } } //return Ok(ToLandTypeViewModel(item_db)); return Content(HttpStatusCode.Accepted, ToLandTypeViewModel(item_db)); }
public static void MyClassInitialize(TestContext testContext) { testItem = new LandTypeViewModel { Id = 0, Type = "地目A" }; newId = 0; }