Reputation: 1726
I have 3 tables; Groups, Customers, and GroupCustomers. Groups can have many customers, hence the reason for the GroupCustomers table. In my C# WinForms program, I am trying to delete all the Customers for a specific Group using Linq. Here's my code that seems to work but it I think I am missing something to make this query a lot smaller/easier/faster to read & execute.
Context.Groups.Where(g => g.Id == group.Id)
.FirstOrDefault()
.Customers.ToList()
.ForEach(gc =>
{
Context.Groups.Where(g => g.Id == group.Id)
.FirstOrDefault()
.Customers.Remove(gc);
});
Context.SaveChanges();
group.Id
is a variable that is passed into this method.
Upvotes: 1
Views: 82
Reputation: 134841
Write a query to select all the items you wish to remove. You wish to remove all customers that are within a particular group. That would correspond to the GroupCustomers
that was created to link the two. Select those, then remove them.
var toBeRemoved =
from gc in Context.GroupCustomers
where gc.GroupId == group.Id
select gc;
foreach (var gc in toBeRemoved)
Context.GroupCustomers.DeleteObject(gc);
Context.SaveChanges();
Otherwise, what you have is logically fine, but I would make a few adjustments. Select the group to remove customers from and remove the customers from the group. .ToList().ForEach()
should never be used as a substitute for a regular call to foreach
.
var removeFromGroup = Context.Groups.FirstOrDefault(g => g.Id == group.Id);
foreach (var c in removeFromGroup.Customers)
removeFromGroup.Remove(c);
Context.SaveChanges();
Upvotes: 0
Reputation: 635
I think you're too stuck on LINQ. I'd write this:
var group = Context.Groups.First(g => g.Id == group.Id); // if you're sure of existing
foreach (var customer in group.Customers.ToList()) // ToList is required to avoid 'Collection was modified' exception, I think
Context.Customers.Remove(customer);
Context.SaveChanges();
Upvotes: 1