Solved

delete collection with entity framework 4 self traking

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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

840 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