Add & Create ODD behaviour
I am new to Entity Framework ORM and am confused with the below. I am confused that my count in MessageBox both after AddObject and CreateObject is same as before adding??? Is this some expected behavior with any ORM? Thanks a bunch in advance.
// Sample Code MessageBox.Show("Count before assignment " + _ctxEntitiesHR.GROUPS.Count()); // Try Add GROUPS newGroup = new GROUPS(); newGroup.GRP_ID = 187; newGroup.GRP_NAME = "group with ID 187"; _ctxEntitiesHR.GROUPS.AddObject(newGroup); // Try Create var newGrp = _ctxEntitiesHR.GROUPS.CreateObject(); newGrp.GRP_ID = 189; newGrp.GRP_NAME = "group with ID 189"; _ctxEntitiesHR.GROUPS.Attach(newGrp); MessageBox.Show("Count after assignment " + _ctxEntitiesHR.GROUPS.Count());
Try calling context.SaveChanges() before requesting the count.
I suspect the Count() will always run a query on the database, while your newly added item hasn't been saved yet.