views:

8

answers:

1

Say I have a CheckBoxList on a page reflecting table data. A user unchecks previously checked items, and checks ones that were not checked. I want to update the database with LINQ2EF so that the records remaining match the newly submitted checked items.

In other words, when the page submits, I get a String[] of checked IDs. I then need to update the database to:

  1. Delete records that were there, but now don't have an ID
  2. Add records that were not there, but now have IDs checked
  3. Leave records that were there, and that are still checked, alone.

Compounding the problem, the submitted Ids are in an array of strings, but the data objects have Id as an int.

A: 

Um, you write code.

var submittedAsInts = submittedAsString.Select(s => int.Parse(s));
var toAdd = submittedAsInts.Where(i => !existingEntity.SomeProperty.Any(p => p.Id == i));
var toDelete = existingEntity.SomeProperty.Where(p => !submittedAsInts.Contains(p.Id));
foreach (var delId in toDelete)
{
    var o = existingEntity.SomeProperty.Single(p => p.Id == delID);
    existingEntity.SomeProperty.Remove(o);
    Context.DeleteObject(o);
}
// similarly for insert.
Craig Stuntz