I'm using EF 4 STE's to model an Attachment object. The Attachment contains a Name, Description, Date, and most importantly Data (byte[]). To optimize loading, I don't want to retrieve the Data property until it's absolutely necessary, i.e. when the user clicks Download from the client.

In an effort to follow this approach, I used the table-splitting technique described here. I split my Attachment table up into Attachment (Name, Description, Date) and AttachmentData (Data). It's a 1-to-1 relationship in my EF model. Everything works great until I try to delete an Attachment without the AttachmentData (i.e. attachment.AttachmentData == null). I get the following exception:

Invalid data encountered. A required relationship is missing. Examine StateEntries to determine the source of the constraint violation.

I saw a similar post, but I can't seem to make it work with STE's and the ApplyChanges extension method.

Right now my data access code is simple: I call context's ApplyChanges() followed by SaveChanges().

I've tried a simple delete SQL function and mapped it to both entities and that actually worked; however it broke the insert. I can't seem to map an insert function for all properties to both entities.

Any ideas on some other options I can try? Can the relationship between Attachment and AttachmentData be optional? When I make it 1 to 0+, I get a mapping error saying that Their primary keys may collide.

Open to any suggestions.

Thanks!

有帮助吗?

解决方案

The solution is similar to linked question but you must use specific feature of STEs - ApplyChanges:

context.Attachments.ApplyChanges(att);
if (context.ObjectStateManager.GetObjectStateEntry(att).State == EntityState.Deleted)
{
    var data = new AttachmentData() {Id = att.Id};
    context.AttachmentDataSet.Attach(data);
    context.AttachmentDataSet.DeleteObject(data);
}
context.SaveChanges();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top