views:

32

answers:

1

I have to entities: Company and Location (one to many). When I create new Location entity object and assign navigation property(Company) with the navigation property of already existing Location object (Location _new = new Location(); _new.Company = _old.Company). It seems that at that point newly created object is added to Object Context automatically, because when I call SaveChanges method that object is insert to database although I didn't call ObjectContext.AddObject(_new). I'm new in EF so there is probably reason why I have result like this? Is there need to assign also CompanyReference filed too and how to do it in order to block this behavior? I want explicitly to add new object myself.

IDaoFactory daoFactory = new DaoFactory();
ILocationDao locaitonDao = daoFactory.GetLocationDao();
IEnumerable<Location> locations = locaitonDao.GetLocations();
Location _old = locations.First();
Location _new = new Location();
_new.LocationName = _old.LocationName;
_new.Company = _old.Company;// 1
_new.Address = _old.Address;
//...
ContactEntities.SaveChanges();//2

If I execute line (1) instantly _new object is added to object context and I can see additional datarow in my datagrid after line (2) is executed.

A: 

That's OK.
"Clever" Entity Framework founds out that you have attached a new object to an object already available in ObjectStateManager and adds the newly attached object to it with the Added state, so it is added on the SaveChanges() call.

Devart
But as said I don't want that. I added new property to Locaiton entity called RelatedCompany to keep reference to specific Company until I decide to save object when I'm going to assign this to navigation property. It works, but I don't know how good is that?
Levelbit