I have three tables Job, Contact and a reference table between them named JobContact. When I delete a record from JobContact table, so record is deleted from database, but it is still present in code. I mean, when I do a select Job by key and when I’m accessing job.JobContact, so record is still there.
How can I force EF to get the current data from this table?
Edited:
I’m using EF to delete the record. Here is a code sample how I’m doing it:
Step 1: delete record from JobContact:
var jobContactRepos = RepositoryFactory.GetRepository<JobContact>();
var jobContact = jobContactRepos.SelectByKey(jobContactId);
jobContactRepos.Delete(jobContact);
jobContactRepos.Save();
Step 2: get the job record from DB after step 1 is done:
var jobRepos = RepositoryFactory.GetRepository<Job>();
var job = jobRepos.SelectByKey(id);
After Step 1, record is deleted from DB: it is OK.
After Step 2, record is still present in the job.JobContact entity: it is not OK.
RepositoryFactory creates already a new context. So I don’t understant. In which place in my code should I use Refresh() method?
thanks
You can dispose your EF context and create a new one, this will force EF to get fresh data from the DB instead of using possibly cached data. Alternatively you can call
Refresh()on your context usingRefreshMode.StoreWins.But the real question is why do you delete this record from the database directly and don’t use EF for it? Had you used the EF context to remove the
Contactentity from theContactsnavigation property collection of yourJobentity, this problem shouldn’t be there in the first place.Edit:
The reference table should be represented in EF as a navigation property
Contactsin yourJobentities, and a navigation propertyJobsin yourContactentities. Are you using an older version of EF (I am probably not familiar enough with previous versions) or have a custom repository layer that introduces this reference entity?