Deleting object with child relationships using .Net Entity Framework issue
Oh my god, EF is so frustrating. I can't seem to figure out what I need to do to remove the object. I seem to be able to delete an object, but not associated child objects. Can anyone tell me what the rule is when you want to delete all related child objects of a given object?
I've tried loading all related objects like this:
Entry entry = ModelContext.GetObjectByKey(new EntityKey("ModelContainer.EntrySet", "Id", id)) as Entry;
entry.ChildEnteries.Load();
if (entry != null)
{
ModelContext.DeleteObject(entry);
ModelContext.SaveChanges();
}
I am getting errors related to relationships: A relationship is being added or deleted from an AssociationSet 'EntryEntry'. With cardinality constraints, a corresponding 'Entry1' must also be added or deleted.
Why can't I just load the object with modelcontext.GetObjectByKey
and delete it along with my child objects?
My other question is, can I delete an entity using the Entity command like so?
DELETE e from objectset as e where e.id = 12
I've tried several options and they all throw exceptions.
source to share
If you are not using cascading deletes, you will need to delete objects that are independently referenced.
Then I think you want something like this:
ObjectSet os = ModelContext.ObjectSet.First(x => x.id == 12);
ModelContext.DeleteObject(os);
ModelContext.SaveChanges();
You can also do cascading deletes on the entity framework, but make sure you set it up in your SQL and then make sure you update the data source from the EDMX file. In particular, make sure the CSDL part has the following :
<Association Name="FK_ItemChildren_Item">
<End Type="Model.Item" Role="Item" Multiplicity="1">
<OnDelete Action="Cascade"></OnDelete>
</End>
<End Type="Model.ItemChildren" Role="ItemChildren"
Multiplicity="*">
</End>
</Association>
source to share