Based on information from here.
I found how deleting orphans with 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 make generic function for this part because it might be used often:
context.ReportCards
.Local
.Where(r => r.Student == null)
.ToList()
.ForEach(r => context.ReportCards.Remove(r));
I thought about 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 it doesn't work. Any advice?
You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore . DataStore<string> store = new DataStore<string>(); Above, we specified the string type in the angle brackets while creating an instance.
LINQ queries are based on generic types, which were introduced in version 2.0 of . NET Framework. You do not need an in-depth knowledge of generics before you can start writing queries.
A generic method is a method that is declared with type parameters, as follows: C# Copy. static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } The following code example shows one way to call the method by using int for the type argument: C# Copy.
All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!
You can write extension method which does the same:
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 this way
context.ReportCards.RemoveOrphans(r => r.Student == null);
context.SaveChanges();
You can also use simple generic method which accepts IDbSet<TEntity>
as first parameters, but it will not be such readable
RemoveOrphans(context.ReportCards, r => r.Student == null);
context.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With