此问题与我以前提出的问题类似。当我使用实体框架(EF)查询数据时,我总是使用MergeOption.NoTracking
选项,因为我最终获取了EF生成的对象并将它们映射到查看模型,该模型在属性上装饰了可爱属性以强制进行验证等等。添加与实体框架的外键关系
我尝试添加使用EF一个外键关系,但只要我做我得到以下异常:
The object being attached to the source object is not attached to the same ObjectContext as the source object
这里是我的代码:
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();
}
}
尝试这样:var productVersion = new ProductVersion(){Id = productVersionId}; supportContext.ProductVersions.AttachTo(“ProductVersions”,productVersion); – 2012-02-28 16:05:46
@DmitrySavy - 我认为你的意思是'supportContext.AttachTo(“ProductVersions”,productVersion)'。但是,是的,这是诀窍,但我真的不明白为什么。 'AttachTo'与'ProductVersions.Attach'有什么不同?我也不喜欢这个解决方案,因为现在代码不是很强类型的,而且编译时可能会忽略一个变化。 – 2012-02-28 16:18:15