Cascade delete and detached objects in Entity Framework?
Here is a part of an Entity Framework model
Basically I have items that can have multiple previews, and each preview has a thumbnail (stored in the blob field Data in PreviewThumbnail).
I am usi开发者_运维知识库ng self-tracking POCO proxies and the repository pattern. Foreign key constraints are enforced both in the database and the Entity Framework model. Now, because the PreviewThumbnail objects contain byte arrays I do not want Entity Framework to track them, I just want to be able to load the bite [?] array and do stuff with it and dispose of it in a while. And this is the relevant code:
public ObjectSet<PreviewThumbnail> PreviewThumbnails {
get {
if (mPreviewsThumbnailsSet == null) {
mPreviewsThumbnailsSet = CreateObjectSet<PreviewThumbnail>("PreviewThumbnails");
mPreviewsThumbnailsSet.MergeOption = MergeOption.NoTracking;
}
return mPreviewsThumbnailsSet;
}
}
And this is how I get the bytes for a given preview:
public byte[] LoadImagePreviewThumbnail(Preview preview) {
var thumb = this.ObjectContext.PreviewThumbnails.First(t => t.Preview.ID == preview.ID);
return thumb.Data;
}
Now then, as the scene is set up, I am trying to get the delete cascade to work - if an Item is deleted, all its Previews should also be deleted along with their PreviewThumbnails. Sound good, but when an Item is deleted, the following exception is thrown:
A relationship from the 'FK_PreviewThumbnails_0' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'PreviewThumbnails' must also in the 'Deleted' state.
If I remove the Cascade OnDelete action from 'FK_PreviewThumbnails_0' exactly the same exception is thrown.
More surprisingly (at least to me), when I change the multiplicity on the PreviewThumbnail end (meaning a preview could not have a thumbnail, which of course is not valid) exactly the same exception is thrown.
The last thing I tried was to completely remove the association between Preview and PreviewThumbnail in the Framework model (after all I can do without it), but that is not valid - the foreign key in the database should be backed by an association in the conceptual model.
Is there a nice way out of this situation?
精彩评论