Entity Framework Split Table Delete
Asked Answered
S

1

13

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!

Scorify answered 17/11, 2011 at 16:46 Comment(0)
A
6

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();
Asher answered 18/11, 2011 at 13:53 Comment(2)
This is what baffles me profoundly: why can't EF figure out that, since the entities are stored in the same table, deleting one of them will also delete the other? Why do you need to load it?Robotize
@FyodorSoikin: I guess because nobody has implemented that feature yet.Asher

© 2022 - 2024 — McMap. All rights reserved.