So I'm trying to update a model. Here's how my models are set up:
public class Event{
public int Id {get;set;}
public string Name {get;set;}
public DateTime Date {get;set;}
public int Organizerid {get;set;}
public virtual User Organizer {get;set;}
}
public class Organizer{
public int Id {get;set;}
public string Name {get;set;}
pubilc virtual iCollection<Event> Events {get;set;}
}
Now I created a ViewModel for the Event (EventViewModel) as whenever I return the regular Event it would throw a loop error on me and I have to use a [JsonIgnore] on every virtual that I have on each model that I pull up. Also, it prevents the web api to return too much info about the current model. Info that is not needed.
My ViewModel
public class EventVM {
public string Name {get;set;}
public DateTime Date {get;set;}
}
With that said, this is how I handled my PUT
[HttpPut]
public HttpResponseMessage Put(int eventId, EventVM event)
{
if (ModelState.IsValid && eventId== event.Id)
{
try
{
Event upEvent = dbcontext.Event.FirstOrDefault(e => e.Id == eventId);
upEvent.Name = eventVM.Name;
upEvent.Date = eventVM.Date;
dbcontext.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}catch(Exception ex){
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
My problem is that it's not saving the updates. I would do a TryUpdateModel but it doesn't seem like it can be used with WebApi. Help! Thoughts?