Click here to Skip to main content
13,298,965 members (41,743 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


2 bookmarked
Posted 12 Apr 2014

EF Remove If Exists

, 12 Apr 2014
Rate this:
Please Sign up or sign in to vote.
Removing entity if it exists


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)

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))

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

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


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Robert Lindblom
Software Developer (Senior)
Sweden Sweden
Working as an independent software contractor, specializing in .Net technologies.

You may also be interested in...

Comments and Discussions

Generalnice Pin
Sk8tz14-Apr-14 10:49
memberSk8tz14-Apr-14 10:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 12 Apr 2014
Article Copyright 2014 by Robert Lindblom
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid