Component expressions that return object instances in the Entity Framework friendly interface

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

They are devoid of all properties that are not related to the problem. The expressions on both of these classes are safe to use as predicates when building LINQ to EF queries. Now let's say that I want to add a method NewestBarValueIsto the class Foo. It might 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, nevertheless, the lambda returned NewestBarValueIsis of the same code, and Foo.GetNewestBarand Bar.ValueIs. If we returned Funcs instead of Funcs expressions, the body NewestBarValueIswould be pretty trivial to write:

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

Funcs . , , , , . , Foo.NewestBarValueIs , Entity Framework ?

+4

Source: https://habr.com/ru/post/1658989/


All Articles