65.9K
CodeProject is changing. Read more.
Home

EF Remove If Exists

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Apr 12, 2014

CPOL
viewsIcon

15545

Removing entity if it exists

Introduction

This small tip offers a solution to a "problem" that kind of annoyed me. The scenario is that you need to remove record(s) from the database, that might exist based on some predicate. You then use DbSet<T>.Remove(), but since DbSet<T>.Remove() can't handle a null parameter you can't do:

context.EntitySet.Remove(context.EntitySet.SingleOrDefault(e => <some predicate>)); 

Instead you need to do something like:

T entity = context.EntitySet.SingleOrDefault(e => <some predicate>);
if(entity != null)
{
    context.EntitySet.Remove(entity);
} 

The Code

To make the above a bit more straight forward, I wrote this simple extension method:

static class DbSetExtensions
{
    public static void RemoveIfExists<T>(this DbSet<T> 
    theDbSet, Expression<Func<T, bool>> thePredicate) where T : class
    {
        foreach(T entity in theDbSet.Where(thePredicate))
        {
            theDbSet.Remove(entity);
        }
    }
} 

Using this extension method, the removal can be made like e.g.:

context.EntitySet.RemoveIfExists(e => e.PropA == 1 && e.PropB > 2);