Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddObject necessary in Entity Framework?

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

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 behaviour works?

like image 548
Koen Avatar asked Jan 31 '26 12:01

Koen


1 Answers

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
like image 110
Koen Avatar answered Feb 03 '26 01:02

Koen