4

Suppose I have two classes that look like this:

public class Foo
{
    public ICollection<Bar> Bars { get; set; }

    public static Expression<Func<Foo, Bar>> GetNewestBar()
    {
        return foo => foo.Bars.OrderByDescending(bar => bar.DateCreated).FirstOrDefault();
    }
}

public class Bar
{
    public string Value { get; set; }
    public DateTime DateCreated { get; set; }

    public static Expression<Func<Bar, bool>> ValueIs(string value)
    {
        return bar => bar.Value == value;
    }
}

These are stripped of all properties that don't pertain to the problem at hand. The Expressions on both of these classes are safe to use as predicates when composing LINQ to EF queries. Now let's say that I want to add a method called NewestBarValueIs to the Foo class. It could look like this:

    public static Expression<Func<Foo, bool>> NewestBarValueIs(string value)
    {
        return foo => foo.Bars.OrderByDescending(bar => bar.DateCreated)
                              .FirstOrDefault()
                              .Value == value;
    }

This is a simple example, but nonetheless, the lambda returned by NewestBarValueIs is composed of the exact same code as Foo.GetNewestBar and Bar.ValueIs. If we were returning Funcs instead of Expressions of Funcs, the body of NewestBarValueIs would be fairly trivial to write:

       return foo => Bar.ValueIs(value)(GetNewestBar()(foo));

Using Expressions of Funcs to achieve this has me stumped. All the code examples that I've found compose multiple logical expressions, not expressions that return instances of objects. So how would one write Foo.NewestBarValueIs in a way that plays nice with Entity Framework using Expressions?

joelmdev
  • 11,083
  • 10
  • 65
  • 89
  • It would be nice if this question was re-opened so I could show how I solved it and reference Servy's related answer. – joelmdev Oct 27 '16 at 17:02

0 Answers0