开发者

Deleting entity with child relationships using .Net Entity Framework problem

My God, EF is so frustrating. I can't seem to be able to get my head around what I need to do so I can delete an object. I seem to be able to remove the object but not the related child objects. Can anyone tell me what is the rule of thumb 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 get errors 开发者_StackOverflow社区related to the 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 using modelcontext.GetObjectByKey and remove it along with its child objects?

My other question is can I delete an object using Entity command like so?

DELETE e from objectset as e where e.id = 12

I've tried few variations and all of them throw exceptions.


If you are not using cascade deletes you will have to delete the referenced objects independently.

Then I think you want something like this:

ObjectSet os = ModelContext.ObjectSet.First(x => x.id == 12);
ModelContext.DeleteObject(os);      
ModelContext.SaveChanges();

You can do cascade deletes in the entity framework too, but make sure you set it up in your SQL and then make sure you update from data source from the EDMX file. In particular make sure 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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜