如何使用LINQ创建泛型函数?

时间:2017-01-30 13:24:47

标签: c# entity-framework linq generics

基于here的信息。

我找到了如何使用Entity Framework删除孤儿。

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

    context.SaveChanges();
}

我想知道如何为这部分制作通用功能,因为它可能经常使用:

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

我想到了这样的事情:

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

但当然它不起作用。有什么建议吗?

2 个答案:

答案 0 :(得分:6)

您可以编写具有相同功能的扩展方法:

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

并以这种方式使用

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

你也可以使用简单的通用方法接受IDbSet<TEntity>作为第一个参数,但它不会那么可读

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

答案 1 :(得分:1)

这样的事情应该有效:

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();
}

用法:

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