Showing posts with label extension method Remove multiple rows dbSet dbContext. Show all posts
Showing posts with label extension method Remove multiple rows dbSet dbContext. Show all posts

Wednesday, October 31, 2012

Remove rows from Entity Framework dbSet based on a condition


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The following extension method used to remove multiple rows (that satisfies a condition) from a dbSet:

using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

public static class DbSetExtension
{
    public static void Remove<TEntity>(this DbSet<TEntity> dbSet,
             Expression<Func<TEntity, bool>> predicate) where TEntity: class
    {

       foreach (TEntity entity in dbSet.Where(predicate).ToList())
       {
           dbSet.Remove(entity);
       }
    }
}

For example, the extension method can be called as follows:


AppDbContext.ProductFeatures.Remove(prodFeature => prodFeature.ProductId == 1432);

The above method call removes all the rows with ProductId = 1432 from ProductFeatures DbSet.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com