How to create a generic function using LINQ?

Based on information from here .

I discovered how to remove orphans using the Entity Framework.

public void SaveChanges() { context.ReportCards .Local .Where(r => r.Student == null) .ToList() .ForEach(r => context.ReportCards.Remove(r)); context.SaveChanges(); } 

I was wondering how to create a generic function for this part, because it can be used often:

 context.ReportCards .Local .Where(r => r.Student == null) .ToList() .ForEach(r => context.ReportCards.Remove(r)); 

I thought of something like this:

 public void SaveChanges() { RemoveOrphans(Student, ReportCards) context.SaveChanges(); } private void RemoveOrphans<T>(T sourceContext, T orphan) { context.orphan .Local .Where(r => r.sourceContext == null) .ToList() .ForEach(r => context.orphan .Remove(r)); } 

But of course this will not work. Any tips?

+6
source share
2 answers

You can write an extension method that does the same thing:

 public static void RemoveOrphans<TEntity>(this IDbSet<TEntity> entities, Func<TEntity, bool> orphanPredicate) where TEntity: class { entities.Local.Where(orphanPredicate).ToList().ForEach(e => entities.Remove(e)); } 

And use it that way

 context.ReportCards.RemoveOrphans(r => r.Student == null); context.SaveChanges(); 

You can also use a simple general method that takes IDbSet<TEntity> as the first parameters, but it will not be so readable

 RemoveOrphans(context.ReportCards, r => r.Student == null); context.SaveChanges(); 
+6
source

Something like this should work:

 private void RemoveOrphans<T>(Predicate<T> where) { var items = context.Set<T>().Where(where).ToList(); if (items != null) { foreach (var item in items) { context.Set<T>().Remove(item); } } context.SaveChanges(); } 

Using:

 RemoveOrphans<ReportCards>(r => r.Student == null); 
+1
source

Source: https://habr.com/ru/post/1014552/


All Articles