LINQ2SQL:如何通过从 datagridview 检索实体来删除实体?
我有一个 datagridview 并附加了员工列表,如下所示:
IQueryable<Employee> data = (from em in db.Employees
where em.StationID == stationID
select em);
dgvView.DataSource = data;
现在我想通过 datagridview 中选定的行删除特定的员工:
using (PetrolNetwork db = new PetrolNetwork())
{
Employee empl = (Employee)dgvView.CurrentRow.DataBoundItem;
db.Employees.DeleteOnSubmit(empl);
db.SubmitChanges();
}
毫不奇怪,我遇到了异常“无法删除尚未附加的实体。”
当我将此代码替换为:
Employee employee = (from em in db.Employees
where em.ID == empl.ID
select em).Single();
db.Employees.DeleteOnSubmit(employee);
db.SubmitChanges();
一切正常,但是 在 sqlprofiler 中,我们可以看到对数据库的一个额外选择来检索我们的特定员工,然后从语句中删除。
我怎样才能当我从 datagridview 的 DataBoundItem 获取员工而无需任何额外的 select 语句时,删除我的员工?我看到的一种方法是自定义存储过程按 ID 删除。可能还有其他最好的方法吗?
I have a datagridview and attached list of Employees to it, somthing like this:
IQueryable<Employee> data = (from em in db.Employees
where em.StationID == stationID
select em);
dgvView.DataSource = data;
Now I want to delete specific Employee by selected row in datagridview:
using (PetrolNetwork db = new PetrolNetwork())
{
Employee empl = (Employee)dgvView.CurrentRow.DataBoundItem;
db.Employees.DeleteOnSubmit(empl);
db.SubmitChanges();
}
Not surprise, that I've got exception "Cannot remove an entity that has not been attached."
When I replace this code by:
Employee employee = (from em in db.Employees
where em.ID == empl.ID
select em).Single();
db.Employees.DeleteOnSubmit(employee);
db.SubmitChanges();
all work correctly, but in sqlprofiler we can see one extra select to database to retrieve our specific employee, and then delete from statement.
How I can delete my employee, when I got it from DataBoundItem from datagridview without any extra select statements? One approach that I can see is custom sproc to delete by ID. May be there is any other best approaches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,使用 LinqToSql,您需要在删除之前选择要删除的项目。
使用您提到的存储过程是一种选择。
另一种是使用 L2S 执行 自定义 SQL 语句。
Unfortunately with LinqToSql, you need to select the item to delete before deleting it.
Using stored procedures as you mentioned is one option.
Another is using L2S to execute custom SQL statements.