Search code examples
c#entity-frameworktelerik-gridicollection

Linq Remove an uncommitted entity from an Entity Collection - How do you find the right one?


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);
}

Solution

  • 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);
    }