Solved

delete collection with entity framework 4 self traking

Posted on 2010-08-15
2
1,362 Views
Last Modified: 2013-11-11
Hi all,
I'm having  some problem deleting entities that contain collections.
Let's say I have an entity called User that contains the following properties: BankAccount, Appointments (that is a List of Appointment), and Friends (list of Friend).
I have to delete (possibly in one call to the db) al the graph.
The function to delete the user is something like that:

public bool DeleteUser(int userId)
{
                    var user = context.Users
                                        .Include("BankAccount")
                                        .Include("Appointments ")
                                        .Include("Friends ")
                                        .Where(u => u.Id == userId)
                                        .FirstOrDefault();
                    if (user != null)
                    {
                        if (user.BankAccount!= null)
                        {
                            context.DeleteObject(user.BankAccount);
                        }

                        // Until the code above all fine.
                        // Now the problem starts deleting the collections
                        // If I use the following if
                        // I have an exception saying that user.Appointments doesn't exist on the context

                        if (user.Appointments != null)
                        {
                            context.DeleteObject(user.Appointments);
                        }

                        // If I use the following doesn't work because of course the enumeraion changes after the first deleting

                        if (user.Appointments != null)
                        {
                            foreach (var appointment in user.Appointments )
                                   context.DeleteObject(appointment);
                        }

                        context.DeleteObject(user);
                        context.SaveChanges();
                    }
}

Open in new window


So which is the best way of deleting entities with properties that are collections?
Also there is any way of saying: this is the main entity, delete it with all the connected entities in just one line? Something like: context.DeleteObject(user) and all the connected collection are deleted?
I'm using EF 4 and self tracking T4 template.

Thanks
0
Comment
Question by:xtremereality
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 3

Accepted Solution

by:
with earned 500 total points
ID: 33446570
for (int i = user.Appointments.Count() - 1; i > -1; i--)
      context.DeleteObject(user.Appointments[i]);

Try walking the collection "backwards" by index, deleting from last to first.

This is a useful technique to remember for times when you must iterate over a collection for the purposes of removing items from that collection.  It's works because you do not invoke an IEnumerator (because you do not use foreach), and if the list changes size, it's ok because because loop variable i is always getting smaller.
0
 
LVL 25

Expert Comment

by:apeter
ID: 33447661
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question