在EF4中删除实体,而不加载整个实体 [英] Delete entity in EF4 without loading the entire entity
问题描述
我在MySql中有一个表,其元数据字段是一个blob字段。使用表分割技术描述这里我将表分为两个实体(DataItem和DataItemDetails)。这样我可以加载所有元数据而不加载blob。
问题是当我尝试删除一个dataitem实体时,我得到这个例外:
异常:
System.Data.UpdateException:遇到
数据无效。缺少必需的
关系。检查
StateEntries以确定限制违规的源
。
如果我转过Lazy Loading或load DataItemDetail部分我可以删除DataItem。
这是可以的,但我不想加载数据只是为了删除它。
if(!D.DataItemDetailReference.IsLoaded)
D.DataItemDetailReference.Load();
_db.DataItems.DeleteObject(d);
_db.SaveChanges();
_db是ObjectContext dereived类,D是DataItem类的一个实例。
如果您不想加载属性必须欺骗EF,所以它认为相关的 DataItemDetail
被加载。
var detailItem = new DataItemDetail {Id = d.Id};
_db.DataItemDetails.Attach(detailItem);
_db.DataItems.DeleteObject(d);
_db.SaveChanges();
这里的问题是表拆分使用1:1关系,EF知道如果删除一个的关系,它也应该删除另一端,但是因为你没有加载其他结束它不能这样做。
I am using entity framework 4 and have the following setup and problem.
I have a table in MySql with metadata fields an a blob field. Using the Table Splitting technique described here i have divided the table into two entities (DataItem and DataItemDetails). This way I can load all the metadata without loading the blobs.
Problem is that when I try to delete a dataitem entity I get this exception:
exception: System.Data.UpdateException: Invalid data encountered. A required relationship is missing. Examine StateEntries to determine the source of the constraint violation.
If I turn of Lazy Loading or load the DataItemDetail part i can delete the DataItem.
This is OK, but I don't want to load the data just to delete it.
if (!D.DataItemDetailReference.IsLoaded)
D.DataItemDetailReference.Load();
_db.DataItems.DeleteObject(d);
_db.SaveChanges();
_db is the ObjectContext dereived class and D is an instance of the DataItem class.
If you don't want to load the property you must trick EF so it thinks that the related DataItemDetail
is loaded.
var detailItem = new DataItemDetail { Id = d.Id };
_db.DataItemDetails.Attach(detailItem);
_db.DataItems.DeleteObject(d);
_db.SaveChanges();
The problem here is that table splitting uses 1:1 relation and EF knows that if it deletes one end of the relation it should also delete other end but because you didn't load other end it can't do it.
这篇关于在EF4中删除实体,而不加载整个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!