0

Using ASP.NET WebAPI, and EF 5.0. I've created a data provider that will query the database and then return an object or collection of objects to my client, which happens to be an html5/angularjs app.

The problem is with the updating. So for example, if I have a Course, which can have many Students. So I have a Course table and a Student table with an fk to StudentId. If I need to edit a student, the EF objects contain everything about a student, including the CourseId, and the Course object itself.

Because of this looping reference, WebAPI pukes when trying to serialize this data, so lazy loading is off- so when I get my Student poco, Course is null.

And then when I update that Student on the client side and then PUT back to my WebAPI, I can't update the DB due to A referential integrity constraint violation occurred.

I could make DTO's but before I go that route are there other patterns I should look at to overcome this problem? Suggestions on other tools or packages to simplify this?

Nicros
  • 5,031
  • 12
  • 57
  • 101

1 Answers1

1

The WebApi struggles serializing the EF object graph but you should be able to update the entity even without navigation properties are null as soon that your object got a valid Id.

Ensure you are attaching it correctly to the context by setting it state to modified:

public void Update(DbContext context, User user)
{
    context.Entry(user).State = EntityState.Modified;
    context.SaveChanges();
}
Giorgio Minardi
  • 2,765
  • 1
  • 15
  • 11
  • Yep I'm doing exactly this :(. The error occurs setting the state to modified, not actually on SaveChanges(). It's interesting you say I should be able to update even with null navigation properties. I wonder if there's something else going on... – Nicros Jul 12 '13 at 19:34
  • The exception indicates there's still some relationship in place. Are the navigation properties of Student decorated with [IgnoreDataMember] ? http://stackoverflow.com/questions/9784507/mvc-4-upshot-entities-cyclic-references – Giorgio Minardi Jul 12 '13 at 19:55
  • 1
    They weren't but I figured it out... you can set `config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;` in Register of WebApiConfig and it ignores null navigation properties... perfect! Thanks for the point in the right direction – Nicros Jul 12 '13 at 21:34