如何使用 ADO.Net 实体框架删除
我无法使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定,但是在附加项目后删除项目之前不需要保存更改吗?
I am not sure, but don't you need to save changes after attaching an item before deleting it?