Solved

delete collection with entity framework 4 self traking

Posted on 2010-08-15
2
1,350 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
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now