CSharp · Console
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
using System.Linq.Dynamic.Core;
using System.Linq;
using var context = new AppDbContext();
// Ensure database is created
await context.Database.EnsureCreatedAsync();
if (!context.Orders.Any())
{
var orders = Enumerable.Range(1, 10).Select(i => new Order
{
Description = $"Order {i}",
Amount = 10.5m * i,
IsProcessed = i % 2 == 0
}).ToList();
foreach (var order in orders)
{
context.Orders.Add(order);
}
await context.SaveChangesAsync();
var filtered = context.Orders
.Where("IsProcessed == @0", true)
.OrderBy("Amount desc")
.Select("new(Description, IsProcessed, Amount)") // dynamic projection
.ToDynamicList();
foreach (var c in filtered)
{
Console.WriteLine($"{c.Description} | {c.IsProcessed} | {c.Amount}");
}
}
public class Order
{
public int Id { get; set; }
public string Description { get; set; }
public bool IsProcessed { get; set; }
public decimal Amount { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));
base.OnConfiguring(optionsBuilder);
}
}
// Output:
// Order 10 | True | 105.00
// Order 8 | True | 84.00
// Order 6 | True | 63.00
// Order 4 | True | 42.00
// Order 2 | True | 21.00