0

So I have this method in a WebAPI controller.

public HttpResponseMessage Post(Model model)
{
   using(var dc = new DataContext())
   {
      dc.MyData.Add(model);
      dc.SaveChanges();
   }   
   //logic that requires the data to be saved first
   using(var dc = new DataContext())
   {
      dc.MyData.Find(model.ID); //this returns null, even tho in the DB I see my model get added to MyData
   }
}

The first using statement saves to the database, however the second using statement can't find the newly added data. In or normal MVC controller the second using statement works as expected.

Is there a reason the second using statement can't find the MyData record from WebAPI?

RJP
  • 4,016
  • 5
  • 29
  • 42
  • take a look what is inside your model.ID property. May be there is a 0 value. Is data stored in database? – syned Sep 10 '13 at 18:25
  • Is Model.ID an Auto Identity key? If so, Model.ID should be populated when you save ([see this question](http://stackoverflow.com/questions/8435462/get-auto-identity-key-after-insert-via-ef)), but if not then we might need to know more about your data model. – Simon C Sep 10 '13 at 21:42

1 Answers1

0

The ID is generated behind the scenes for Entity Framework. Probably the ID you are using has 0, because you got It from the parameter.´

If the Add method succed, this statement above should return the last item inserted, that's what you want:

using(var dc = new DataContext())
{
  var myModel = dc.MyData.Last();
}
Fals
  • 6,813
  • 4
  • 23
  • 43