删除 EF4 中的实体而不加载整个实体
我正在使用实体框架 4 并有以下设置和问题。
我在 MySql 中有一个表,其中包含元数据字段和 blob 字段。使用描述的表拆分技术 此处 我已将表分为两个实体(DataItem 和 DataItemDetails)。这样我就可以加载所有元数据而不加载 blob。
问题是,当我尝试删除数据项实体时,出现以下异常:
异常: System.Data.UpdateException:无效 遇到的数据。必填项 关系缺失。检查 StateEntrys 确定源 违反约束的情况。
如果我关闭延迟加载或加载 DataItemDetail 部分,我可以删除 DataItem。
这没问题,但我不想加载数据只是为了删除它。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不想加载该属性,则必须欺骗 EF,使其认为相关的
DataItemDetail
已加载。这里的问题是表分割使用 1:1 关系,并且 EF 知道如果它删除关系的一端,它也应该删除另一端,但因为你没有加载另一端,所以它不能这样做。
If you don't want to load the property you must trick EF so it thinks that the related
DataItemDetail
is loaded.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.
谢谢拉迪斯拉夫和马库斯!这正是我所需要的。要在 Entity Framework 4.1 中使用 Database First 执行此操作,我必须对其进行如下更改:
Thanks Ladislav and Markus! This is exactly what I needed. To do this in Entity Framework 4.1 with Database First, I had to change it thusly:
有什么原因无法调用存储过程吗? MEF 应该可以处理这些问题,你会没事的 &快速将 ID 传递到存储过程,您可以在其中对数据执行您喜欢的操作。
抱歉...编辑一下,我知道这并不能回答“如何使用 EF4”的问题,但如果您遇到困难,这是一个相当可行的解决方法(并且也很容易实现)。干杯。
Is there any reason you can't make a call to a stored proc? MEF should handle those okay, and you'd be fine & fast to pass an ID to a stored proc where you can do what you like with the data.
Sorry...edit to say, I know this doesn't answer the question "how to with EF4", but if you're stuck this is a fairly viable work around (and easy to implement, too). Cheers.