Hey there,
Ive got a WPF app, following the Model View ViewModel pattern, using the Entity Framework to interact with a SQL 2008 database.
Problem:
My problem is i can't change a foreign key value in the databse using EF. I have two entities: Site and Key. A Site can have many Keys on it. I would like to move a Key from one Site to another. I'm trying to do this using the following code:
keyToMove.Site = newSite;
dataAccess.SaveChanges(); // this method just does: this.entities.SaveChanges();
What I've Observed
It appears in memory everything is fine as the rest of the app reflects this change (the Key will appear under the new Site). However, the foreign key in the database does not change, and upon closing and restarting the app, all changes are lost.
After "keyToMove.Site = newSite;", keyToMove, newSite and the old Site instance all have an EntityState value of "Unchanged" which can't be right. Also SaveChanges is returning 2, which is just confusing me even further.
The setter implementation for the "Site" property looks like other navigation properties in my model:
set
{
((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Site>("CmsModel.SiteKeyAssociation", "Site").Value = value;
}
SQL Profiler shows that nothing resembling an UPDATE is sent to the db engine, only a very, very long SELECT.
Things which may have an effect
The "Key" entity inherits from another entity based on a condition applied to one of the columns.
I'm using the AutoFac IOC container to supply any ViewModels who want to do some data access with a reference to an instance of my data access class ("dataAccess" in the example).
An ObjectContext instance is a member of this class (shown in comments as "this.entities").
The dataAccess instance is Singleton Scoped so there should only be one instance being shared among the View Models e.i. both "keyToMove" and "newSite" are attached to the same context.
Sorry for the length of this post, but i seriously have no idea whats going on here and ive tried to provide as many details which may help as possible. Please ask if any further info would help.
Thanks in advance.