using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace IssueConsoleTemplate
public int Id { get; set; }
public string Phone { get; set; }
public string Name { get; set; }
public int UserId { get; set; }
public WAUser User { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public class Context : DbContext
public DbSet<WAContact> Contacts { get; set; }
public DbSet<WAUser> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
FiddleHelper.GetConnectionStringSqlServer())
.AddFilter(level => level >= LogLevel.Information)))
.EnableSensitiveDataLogging()
protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<WAUser>()
new WAUser {Id = 1, Name = "John"},
new WAUser {Id = 2, Name = "Jane"},
new WAUser {Id = 3, Name = "Mike"});
modelBuilder.Entity<WAContact>()
new WAContact {Id = 11, Name = "John's First Contact", Phone = "12345", UserId = 1},
new WAContact {Id = 12, Name = "John's Second Contact", Phone = "23456", UserId = 1},
new WAContact {Id = 21, Name = "Jane's Only Contact", Phone = "09876", UserId = 2});
private static void Main()
using var context = new Context();
context.Database.EnsureCreated();
var userIdsWithContactsWithoutJoin = context.Contacts
Debug.Assert(userIdsWithContactsWithoutJoin.Count == 2);
Debug.Assert(userIdsWithContactsWithoutJoin[0].Key == 1);
Debug.Assert(userIdsWithContactsWithoutJoin[0].Count() == 2);
Debug.Assert(userIdsWithContactsWithoutJoin[0].First().Name == "John's First Contact");
var userIdsWithContacts = context.Users
.Where(c => u.Id == c.UserId),
.GroupBy(j => j.UserId, j => j.Contact)
Debug.Assert(userIdsWithContacts.Count == 2);
Debug.Assert(userIdsWithContacts[0].Key == 1);
Debug.Assert(userIdsWithContacts[0].Count() == 2);
Debug.Assert(userIdsWithContacts[0].First().Name == "John's First Contact");
var usersWithOrWithoutContacts = context.Users
.Where(c => u.Id == c.UserId)
.GroupBy(j => j.User, j => j.Contact)
Debug.Assert(usersWithOrWithoutContacts.Count == 3);
Debug.Assert(usersWithOrWithoutContacts[0].Key.Name == "John");
Debug.Assert(usersWithOrWithoutContacts[0].Count() == 2);
Debug.Assert(usersWithOrWithoutContacts[0].First().Name == "John's First Contact");