Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

c# - Entity Framework Split Table Delete

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...