I still love me some LINQ.
From time to time, I have to make pages where there are checkable permissions or mappings, for example. In the present app, I'm mapping product manufacturers to retail locations. It's really no big deal. In the old Pre-LINQ world, I could have wrote nested looping structures to find mappings to delete and new mappings to create. (I usually settled for the lazy version of
not trying to find changes but rather deleting everything and recreating the mappings. Not really a problem, but it did needlessly destroy database records just to recreate them.)
With LINQ, I'm able to join a CheckBoxList with my present mapping list and pull out records to delete, and then do a group join to find new records to add. No nested loops, no lazy destruction/recreation. It's all beautiful and simple.
private void ProcessLocationManufacturerMapping(CheckBoxList chkManufacturerList, LocationManufacturers locationManufacturers, int locationID)
{
// join list of location manufacturers with list of non-selected items
var deletes = from locMan in locationManufacturers
join ListItem item in chkManufacturerList.Items
on locMan.ManufacturerID equals int.Parse(item.Value)
where item.Selected == false
select locMan;
foreach (LocationManufacturer locationManufacturer in deletes)
locationManufacturer.Delete();
// join list of selected items with location manufacturers...
// pull the items where the matching location manufacturer does not exist
var adds = from ListItem item in chkManufacturerList.Items
where item.Selected == true
join locMan in locationManufacturers
on int.Parse(item.Value) equals locMan.ManufacturerID
into groupJoin
from locMan2 in groupJoin.DefaultIfEmpty()
where locMan2 == null
select item;
foreach (ListItem item in adds)
{
LocationManufacturer locationManufacturer = new LocationManufacturer();
locationManufacturer.LocationID = locationID;
locationManufacturer.ManufacturerID = int.Parse(item.Value);
locationManufacturer.SaveNew();
}
}

LINQ


.NET


MSFT

I'm still not using LINQ to SQL, though. Not ready to concede control over my data layer.
