且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架拆分表删除

更新时间:2023-02-13 14:43:01

解决方案是类似于链接问题,但您必须使用STE的特定功能 - 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();


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