0

My RadGrid is populated from an entity framework ICollection held in Session State. The primary key is an auto incremented field in the database. A user can add multiple rows to the grid without submitting them to the database. If the user removes a row before saving, how do you find the particular entity to remove? So far, no primary key will be assigned to new rows until the data is actually saved.

DataContext context = (DataContext)Session["context"];

protected void rgEmployees_DeleteCommand(object source, GridCommandEventArgs e) {
    int MyID = Tools.GetInt((e.Item as GridDataItem).
        OwnerTableView.DataKeyValues[e.Item.ItemIndex]["My_ID"]);
    Employee ee= context.Employee.SingleOrDefault(t => t.ID == MyID); 
    // The problem with above line is that t.ID has not been established yet.
    context.Employee.Remove(ee);
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Stoertz
  • 7
  • 6

1 Answers1

0

Assuming the entities will be in the order you add them, I think your only option here is to do it by index i.e.

protected void rgEmployees_DeleteCommand(object source, GridCommandEventArgs e) {
    Employee ee = context.Employee.AsEnumerable().ElementAt(e.Item.ItemIndex); 
    context.Employee.Remove(ee);
}
James
  • 80,725
  • 18
  • 167
  • 237
  • The data does stay in the same order as what's shown on the grid and - with minor edits - this solution worked. – Stoertz Nov 11 '13 at 17:30
  • @Stoertz just bare in mind this code would bring your full `Employee` table into memory with `AsEnumerable`, there is no support for `ElementAt` with EF. – James Nov 11 '13 at 18:29