Pergunta

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?

Foi útil?

Solução

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.

result = db.ExecuteCommand("Delete from Employees WHERE id = '2'")
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top