Skip to content

Instantly share code, notes, and snippets.

@JeremyLikness
Created June 17, 2022 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeremyLikness/4d8a5411cb8d1dffec7ec747969a67b5 to your computer and use it in GitHub Desktop.
Save JeremyLikness/4d8a5411cb8d1dffec7ec747969a67b5 to your computer and use it in GitHub Desktop.
Example of repo with "open" IQueryable
using Example;
using Microsoft.EntityFrameworkCore;
var repo = new ThingRepo();
repo.Init();
var cyanShapes = repo.GetThings(
q => q.Where(
q => q.Name.Contains(nameof(ConsoleColor.Cyan)))
.OrderByDescending(s => s.Size));
foreach(var shape in cyanShapes)
{
Console.WriteLine($"{shape.Name} ({shape.Size})");
}
namespace Example
{
public class ThingRepo
{
public void Init()
{
var random = new Random();
var colors = Enum.GetNames<ConsoleColor>();
var shapes = new[] { "Square", "Circle", "Triangle", "Rectangle" };
using var ctx = new ThingContext();
foreach (var color in colors)
{
foreach (var shape in shapes)
{
var thing = new Thing { Name = $"{color} {shape}", Size = random.Next(1, 200) };
ctx.Things.Add(thing);
}
}
ctx.SaveChanges();
}
public IList<Thing> GetThings(Func<IQueryable<Thing>, IQueryable<Thing>> query)
{
using var ctx = new ThingContext();
var queryToUse = query(ctx.Things);
return queryToUse.ToList();
}
}
public class Thing
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public int Size { get; set; }
}
public class ThingContext : DbContext
{
public DbSet<Thing> Things { get; set; } = null!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("ThingDb");
base.OnConfiguring(optionsBuilder);
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.6" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment