1

This is a common repository delete function. How does C# know which item to delete? Isn't it better to delete by integer ids, primaryid keys? By passing the whole class, does it not taking longer processing time ?

Thanks,

    public void Delete(T entity)
    {
        _dbContext.Set<T>().Remove(entity);
        _dbContext.SaveChanges();
    }

    public void Delete(Foo entity) 
    {
        context.Foos.Remove(entity);
    }
  • EF deletes it by the unique identifier of the entity only. So if the table has primary key column and the entitiy being deleted has the value assigned to the primary key property EF will delete based on that value. No, it doesn't take longer. – Chetan May 29 '18 at 01:41
  • Tip, don't use the repository pattern for EF, you will regret it – TheGeneral May 29 '18 at 02:50
  • @TheGeneral, you don't use repository pattern for EF - you implement repository pattern by using EF – Fabio May 29 '18 at 03:21
  • @Fabio yes indeed. Though it surprises me how prolific these monolithic/generic/sub repository architectures still are. All i can put it down to are teachers working off old blogs/books, or the prevalence of same kicking around the internet – TheGeneral May 29 '18 at 04:39
  • Also: https://stackoverflow.com/a/12880364/861716 – Gert Arnold May 29 '18 at 06:27

1 Answers1

0

How does C# know which item to delete?

Entity framework deletes it by a unique identifier.

Isn't it better to delete by integer ids, primary keys?

Yes, Actually Entity framework also delete a record by its unique id. But we have to provide a complete entity then Entity framework matches the entity ID.

By passing the whole class, does it not taking longer processing time?

Not too much, a few milliseconds, But problem is that two database queries for one operation, one to retrieve the record and second to delete the record.

Solution:

In Entity framework 6.0 you can delete a record without retrieving it. Here is a complete solution.

habib
  • 2,366
  • 5
  • 25
  • 41
  • hi, Thanks just accepted answer, and gave points, can you one up my question also? Thanks, –  May 30 '18 at 06:18