using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using AutoMapper.Extensions.ExpressionMapping;
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Wheel> Wheels { get; set; }
public int Id { get; set; }
public int? FkCar { get; set; }
public int FkBrand { get; set; }
public string Name { get; set; }
public virtual Car Car { get; set; }
public virtual Brand Brand { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Wheel> Wheels { get; set; }
public class CarContext : DbContext
public CarContext(DbContextOptions<CarContext> options)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
base.OnConfiguring(optionsBuilder);
public DbSet<Car> Cars { get; set; }
public DbSet<Wheel> Wheels { get; set; }
public DbSet<Brand> CarBrands { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Wheel>(entity =>
entity.HasOne(d => d.Car)
.HasForeignKey(d => d.Id);
entity.HasOne(d => d.Brand)
.HasForeignKey(d => d.Id);
public int Id { get; set; }
public string Name { get; set; }
public List<int> BrandFks { get; set; }
private CarContext _context;
public CarService(CarContext context)
public void FillDatabase()
Wheels = new List<Wheel> {
Wheels = new List<Wheel> {
static void Main(string[] args)
var optionsBuilder = new DbContextOptionsBuilder<CarContext>();
optionsBuilder.UseSqlServer(FiddleHelper.GetConnectionStringSqlServer());
Console.WriteLine("This is an example of using EF Core InMemory Database");
Console.WriteLine("======================================================");
var config = new MapperConfiguration(
cfg.AddExpressionMapping();
cfg.CreateMap<Car, CarDto>()
.ForMember(dest => dest.BrandFks, opt => opt.MapFrom(source => source.Wheels.Select(x => x.FkBrand)));
var mapper = config.CreateMapper();
using (var context = new CarContext(optionsBuilder.Options))
context.Database.EnsureCreated();
var service = new CarService(context);
var working = context.Cars
.UseAsDataSource(mapper.ConfigurationProvider).For<CarDto>()
.Where(x => x.BrandFks.Any(y => y == 1))
var notWorking = context.Cars
.UseAsDataSource(mapper.ConfigurationProvider).For<CarDto>()
.Where(x => x.BrandFks == null)