private MenuViewModel ToMenuViewModel(Menu item) { return new MenuViewModel { Id = item.Id, Text = item.Text, TimestampString = Convert.ToBase64String(item.Timestamp), ContentUrl=item.ContentUrl, CssClass=item.CssClass, ParentId=item.ParentId}; }
public IHttpActionResult Post(MenuViewModel item_viewModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } Menu item = new Menu { Id = item_viewModel.Id, Text = item_viewModel.Text, ContentUrl=item_viewModel.ContentUrl, CssClass=item_viewModel.CssClass, ParentId= item_viewModel.ParentId}; db.Menus.Add(item); try { db.SaveChanges(); //寫入AccessLog MPAccessLog.WriteEntry(User.Identity.Name, AccessAction.Create, "Menu", JsonConvert.SerializeObject(new { item.Id, item.Text,item.ContentUrl,item.ParentId })); } 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)); } catch (DbUpdateException ex) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.InnerException.Message)); } return CreatedAtRoute("DefaultApi", new { id = item.Id }, ToMenuViewModel(item)); }