Skip to content

Instantly share code, notes, and snippets.

@ScottGuymer
Last active May 24, 2022 22:01
Show Gist options
  • Save ScottGuymer/2d6990719ed99edcce65e226f96a3025 to your computer and use it in GitHub Desktop.
Save ScottGuymer/2d6990719ed99edcce65e226f96a3025 to your computer and use it in GitHub Desktop.
Selector pattern for testable linq statements
using System.Linq;
public class ExampleQuery : ISelect<in Post, out IEnumerable<Post>>
{
public IEnumerable<Post> Run(IQueryable<Post> objects)
{
return objects.Where(x => x.Published);
}
}
using System.Linq;
public class ExampleQueryWithParams : ISelect<in Post, out IEnumerable<Post>>
{
private DateTime startDate;
public ExampleQueryWithParams(DateTime startDate)
{
this.startDate = startDate;
}
public IEnumerable<Post> Run(IQueryable<Post> objects)
{
return objects.Where(x => x.PublishedDate > StartDate);
}
}
using System.Linq;
/// <summary>
/// An Interface to define a selector query that is used to return data from the database.
/// </summary>
/// <typeparam name="TIn">The type of the input to the query.</typeparam>
/// <typeparam name="TOut">The type of the output from the query.</typeparam>
public interface ISelect<in TIn, out TOut>
{
TOut Run(IQueryable<TIn> objects);
}
using System.Linq;
[TestFixture]
public class TestASelector
{
[Test]
public void TestSelector()
{
var data = new List<Post> { new Post() { Published = true } };
var selector = new ExampleQuery();
var result = selector.run(data.AsQueryable());
// assert things about the collection here
}
}
using System.Linq;
public class UseASelector
{
private DBContext db;
public void DoWork()
{
var selector = new ExampleQuery();
var result = selector.run(db.myTable);
var selectorWithParams = new ExampleQueryWithParams(DateTime.Now);
var result2 = selectorWithParams.run(db.myTable);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment