views:

220

answers:

1

I am unable to delete a record from the the table using ADO.Net Entity Framework.
Debugging lets me go through the method without any errors.

Cust_DataModel.Cust_DataEntities db = new Cust_DataModel.Cust_DataEntities();

protected void DeleteButton_Click(object sender, EventArgs e)
{
  if (lvCust.SelectedIndex >= 0)
    {
        int custId = Convert.ToInt32(lvCust.SelectedDataKey.Value.ToString());
        var cust = db.Cust.FirstOrDefault(d => d.CustId == custId );

        try
        {
            int co = db. Cust.Count();
            db.AttachTo("Cust", cust);

            db.DeleteObject(cust);
            int co2 = db. Cust.Count();
            db.SaveChanges();
            int co1 = db. Cust.Count();
        }
        catch (Exception ex)
        {
        }

        lblMessage.Text = "cust was deleted.";
    }
    else
        lblMessage.Text = "No cust was selected.";
}

I am able to list the items from the table into a ListView.

private void BindCust()
{
  var custs = from cust in db.Cust where cust.UserId == userId orderby cust.Created descending select cust;

            lvCust.DataSource = custs;
            lvCust.DataBind();
}
A: 

I am not sure, but don't you need to save changes after attaching an item before deleting it?

Trimack