Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

delete collection with entity framework 4 self traking

Posted on 2010-08-15
2
Medium Priority
?
1,367 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 2000 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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

604 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