如何使用 ADO.Net 实体框架删除

发布于 2024-08-10 05:30:00 字数 1103 浏览 5 评论 0原文

我无法使用 ADO.Net 实体框架从表中删除记录。
调试让我可以顺利地完成该方法。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏佲洛 2024-08-17 05:30:00

我不确定,但是在附加项目后删除项目之前不需要保存更改吗?

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文