views:

39

answers:

1

I have two tables Job (Id, Title) and Employee (Id, Name, JobId). 1-* relationship.

How can I delete Employee that has reference to it's job without retrieving information from the database?

I can do something like that:

var j = new Job { Id = 1 };  // UGLY, I have to create and attach Job instance and job.Id should be exactly the same as id  employee entity reffers to (!) 
e = new Employee { Id = 1, Job = j };  
db.AttachTo("Jobs", e);
db.AttachTo("Employees", e);
db.DeleteObject(e);
db.SaveChanges();

but I want to have something like :

e = new Employee { Id = 1 };  
db.AttachTo("Employees", e);
db.DeleteObject(e);
db.SaveChanges();

Is it possible to construct entity and delete it by id without populating the reference? Attach/Delete approach works ok if entity scheme has no foreign keys

+2  A: 

In EF you need first to load the item, in order to delete it.

You could write a stored procedure to delete an item by id, and then call the stored procedure from EF.

Shiraz Bhaiji
Yes, you are completely right. But I want to avoid additional roundtrip to database.
Andrew Florko
If you implement it using the stored procedure you save the round trip, as long as you have the id of the item that you want to delete.
Shiraz Bhaiji