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




3 comments:

  1. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    rpa training in bangalore
    best rpa training in bangalore
    RPA training in bangalore
    rpa course in bangalore
    rpa training in chennai
    rpa online training

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    python training in rajajinagar
    Python training in bangalore
    Python training in usa

    ReplyDelete
  3. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
    AWS Training in pune
    AWS Online Training

    ReplyDelete