You need to take care of two steps. (1) Add the newly selected values and (2) remove the unselected values. You'll need a method like this in your LookupTable class.
public void SynchronizeDataTables(IEnumerable<DataTable> dataTables)
{
// get the current data tables. call ToList() to force and enumeration.
// without the ToList(), you'll get a "Sequence Changed during Enumeration"
// error
var currentDataTables = MapTable.Select(m => m.DataTable).ToList();
// if the table is selected, but not in the data store add it.
foreach (var dataTable in dataTables)
{
if (!currentDataTables.Contains(dataTable))
{
MapTables.Add(new MapTable { DataTable = dataTable });
}
}
// if the table is in the data store, but not selected, then remove it.
foreach (var dataTable in currentDataTables)
{
if (!dataTables.Contains(dataTable))
{
MapTables.Remove(dataTable);
}
}
}
Edit: When I did this, I was using LINQ-to-SQL, and I cycled through just the selected ID's, instead of the entire object. This is more complicated because LINQ-to-Entities creates slightly different objects than LINQ-to-SQL, because it doesn't expose the FK identity. Slight modification follows:
public void SynchronizeDataTables(IEnumerable<int> dataTableIds)
{
// get the current data tables. call ToList() to force and enumeration.
// without the ToList(), you'll get a "Sequence Changed during Enumeration"
// error
var currentDataTableIds = MapTable.Select(m => m.DataTable.Id).ToList();
// if the table is selected, but not in the data store add it.
foreach (var dataTableId in dataTableIds)
{
if (!currentDataTableIds.Contains(dataTableId))
{
var dataTable = ???; // some method to fetch data table with ID = dataTableId
MapTables.Add(new MapTable { DataTable = dataTable });
}
}
// if the table is in the data store, but not selected, then remove it.
foreach (var dataTable in currentDataTableIds )
{
if (!dataTableIds.Contains(dataTableId ))
{
var dataTable = ???; // some method to fetch data table with ID = dataTableId
MapTables.Remove(dataTable);
}
}
}