Delete entity in EF4 without loading the entire entity

天涯浪子 提交于 2019-12-06 13:03:13

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.

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:

If _db.Entry(d).Reference(Function(e) e.DataItemDetails).IsLoaded() = False Then
     Dim detailItem = New DataItemDetails With { .ID = d.ID }
     _db.DataItemDetails.Attach(detailItem)
End If
_db.DataItems.Remove(d)
_db.SaveChanges()

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!