我无法使用 ADO.Net Entity Framework 从表中删除记录。
调试让我通过该方法没有任何错误。
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.";
}
我能够将表中的项目列出到 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();
}