Reputation: 32778
I am looking at these two examples from two different repositories:
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Deleted)
{
dbEntityEntry.State = EntityState.Deleted;
}
else
{
DbSet.Attach(entity);
DbSet.Remove(entity);
}
}
public virtual void Delete(T entity) {
dbset.Remove(entity);
}
Can someone explain the difference. Why did the author of the first add all the additional lines?
Upvotes: 0
Views: 89
Reputation: 109079
What is the best way for me to perform a delete using EF 6 and a repository?
I can't answer your question. Here's why.
If you want to delete an object through Entity Framework two things must be true:
Deleted
state.The aim of the first Delete
method seems to be to ensure that both conditions will be met after it has run. But that's not as simple as it seems. It has to sniff out the object's current state, attach it if necessary, set its state if necessary. And, not even accounted for yet, it also has to make sure it's not attached to any other context. This, and Anthony Chu's comments show that the first method isn't nearly complex enough yet.
So keep it simple and use the second method? Well, the second method presumes that the calling code knows it's alright to just call dbset.Remove
, it knows all the things the first method tries to find out. But if it's that smart already, why would it be too dumb too call DbSet.Remove
directly? (Aside from the fact that the second method itself is pretty dumb, as Timothy Walters points out).
And then, there are three ways to mark an object as Deleted
:
Remove
it from a DbSet
DbEntityEntry
as Deleted
Remove
it from a parent's child collectionTrying to confine all deletes to calling one repository method may be a great restriction to writing the best code.
That's why I can't answer your question. I don't believe in repository layers on top of DbSet
anyway. So as for me, the best way to perform deletes depends on what the code of each of your use cases looks like.
Upvotes: 1