views:

178

answers:

1

I'm using Entity Framework (1st time) on a SQL 2005 database for a data migration and found this very odd behavior...

Up till now I never had to call the AddObject method to persist new records. SaveChanges always did the trick, so I figured the entity constructor always hooked the new entity to the data context.

Now I added migration for another entity type and suddenly only about 20% of those records are persisted, so now I do have to call the AddObject method for that entity type. Anyone can explain how this behavior works?

tnx

+2  A: 

Looks like Entity Framework attaches a new entity when you call a setter on one of its properties and set it to an already attached (e.g. loaded through the same context) entity reference.

So:

var myEntity = new MyEntity { Name = "name" }; // will not implicitly add the entity to the context
var myEntity = new MyEntity { OtherEntity = someAttachedEntity }; // will implicitly add the entity to the context
Koen
That sounds about right. Consider if you just create new it has absolutely no relationship to the context, hence the need to add.
Doobi