Skip to content

Instantly share code, notes, and snippets.

@lukemcgregor
Last active May 28, 2018 04:42
Show Gist options
  • Save lukemcgregor/692834629da09b21d5a35515e86c9002 to your computer and use it in GitHub Desktop.
Save lukemcgregor/692834629da09b21d5a35515e86c9002 to your computer and use it in GitHub Desktop.
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace EfSelectIssue
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
using (var ctx = new MyContext())
{
var anEntity = new A();
ctx.As.Add(anEntity);
ctx.Bs.Add(new B() { A = anEntity, Name = "1" });
ctx.Bs.Add(new B() { A = anEntity, Name = "2" });
ctx.Bs.Add(new B() { A = anEntity, Name = "3" });
ctx.SaveChanges();
foreach (var thing in ctx.As
.Select(a => new
{
AId = a.Id,
BNames = a.Bs.Select(x => x.Name)
}))
{
Console.WriteLine(thing.AId + ":" + String.Join(", ", thing.BNames));
}
}
}
}
public class MyContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=.\;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true");
}
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
}
public class A
{
public int Id { get; set; }
public ICollection<B> Bs { get; set; }
}
public class B
{
public int Id { get; set; }
public string Name { get; set; }
public A A { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment