This problem is similar to my previously asked question. When I query data using the Entity Framework (EF) I always use the MergeOption.NoTracking option because I end up taking my EF generated objects and mapping them to view models which have lovely attributes decorated on the property to enforce validation and so on.
I am trying to add a foreign key relationship using the EF, but anytime I do I am getting the following exception:
The object being attached to the source object is not attached to the same ObjectContext as the source object
Here is my code:
public static void UpdateDownloadFileVersion(DownloadFile downloadFile, int[] selectedVersions) {
using (SupportEntity supportContext = new SupportEntity()) {
supportContext.DownloadFiles.Attach(downloadFile);
var productVersionIdsToAdd = (from v in selectedVersions
where (downloadFile.ProductVersions.Any(pv => pv.Id == v) == false)
select v).ToList();
foreach (var productVersionId in productVersionIdsToAdd) {
var productVersion = new ProductVersion() { Id = productVersionId };
downloadFile.ProductVersions.Attach(productVersion); //Exception happens here.
downloadFile.ProductVersions.Add(productVersion);
}
supportContext.SaveChanges();
}
}
This is where Stub Entities become very very useful…
Here is a good article
In above case, when attached
productVersionis assigned toproduct versions‘ entity, productversion entity gets attached to context, withEntityState=Added. Entire graph will be in or out of context.