【问题标题】:How to make generic function using LINQ?如何使用 LINQ 制作通用函数?
【发布时间】:2017-01-30 13:24:46
【问题描述】:

基于来自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));
}

但它当然行不通。有什么建议吗?

【问题讨论】:

  • 对于Where 部分,只需传入Predicate
  • 你可能想使用context.Set&lt;T&gt;

标签: c# entity-framework linq generics


【解决方案1】:

你可以编写扩展方法来做同样的事情:

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&lt;TEntity&gt; 作为第一个参数,但它不会那么可读

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

【讨论】:

  • .ToList() 并不懒惰。使用.AsEnumerable() 并编写一个foreach 循环。
  • @Oliver 在这种情况下你会得到InvalidOperationException - 你不能修改枚举的集合
【解决方案2】:

这样的事情应该可以工作:

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

【讨论】:

  • items 永远不能是 null(但为空)。所以不需要空检查。
猜你喜欢
  • 1970-01-01
  • 2019-11-16
  • 2010-12-10
  • 2012-11-08
  • 2020-09-25
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多