Andrew Florko
Andrew Florko

Reputation: 7750

EF. Delete entity by Id that has foreign key

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

Upvotes: 1

Views: 531

Answers (1)

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65361

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.

Upvotes: 2

Related Questions