LINQ: Passing lambda expression as parameter to be executed and returned by method

前端 未结 3 641
悲&欢浪女
悲&欢浪女 2020-11-28 06:53

So here is the scenario: i have a series of different repository classes that each can use an isolated data context, or a shared context. In the cases where an isolated cont

3条回答
  •  攒了一身酷
    2020-11-28 07:37

    Something like this:

    public IEnumerable ExecuteInContext(
      Expression> predicate)
    {
      ... // do your stuff
      //eg
      Table t = GetTable();
      return t.Where(predicate);
    }
    

    or

    public IEnumerable ExecuteInContext(
       IQueryable src, Expression> predicate)
    {
      return src.Where(predicate);
    }
    

    Usage:

    var r = repo.ExecuteInContext( 
              x => x.SomeProp.Equals(Somevalue));
    

    or

    var r = repo.ExecuteInContext(GetTable(), 
              x => x.SomeProp.Equals(Somevalue));
    

    Assumptions:

    1. Table can be derived from T, else you will need to pass the source too.
    2. You know how to modify the predicate expression if needed.

提交回复
热议问题