0

Say I have a database entities structure like this

public class Parent
{
    public virtual Child Child { get; set;}
}

public class Child
{
    public string Property_1 { get; set; }
}

Now say I have two linq queries like this

var children = _context.Child.Where(c => c.Property_1 == "X").ToList();
var parents = _context.Parent.Where(p => p.Child.Property_1 == "X").ToList();

The where condition in both the cases are in once sense exactly same.

Now I can put the first condition in a separate function which will return expression and then I can use it whenever I want to select child with this condition.

But even though the second condition while selecting parent is also same but I will still not be able to use the same expression function for the where clause because it will accept the object of type Child.

So my question is, is there any possibility to put the where condition in a separate function in such a way that it can be used with both the linq queries?

Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105
  • This [question](https://stackoverflow.com/q/8718480/1136044) is most likely related to what you are looking for. – chris05 Nov 25 '21 at 20:35

1 Answers1

0

You can use LINQKit for such task, which can expand reusable methods.

public static class QueryExtensions
{
    [Expandable(nameof(IsXValueImpl))]
    public static bool IsXValue(this Child child)
    {
        throw new NotImplementedException();
    }

    private static Expression<Func<Cahild, bool>> IsXValueImpl()
    {
        return child => child.Property_1 == "X";
    }
}

And usage:

var children = _context.Child.Where(c => c.IsXValue()).ToList();
var parents = _context.Parent.Where(p => p.Child.IsXValue()).ToList();

LINQKit can be activated during options building:

builder
    .UseSqlServer(connectionString)
    .WithExpressionExpanding(); // enabling LINQKit extension

Or by AsExpandable() extension:

var children = _context.Child.AsExpandable().Where(c => c.IsXValue()).ToList();
var parents = _context.Parent.AsExpandable().Where(p => p.Child.IsXValue()).ToList();
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32