Skip to content

Instantly share code, notes, and snippets.

@corruptmem
Last active May 18, 2018 14:22
Show Gist options
  • Save corruptmem/80c673a629dd3e0ce26a360ae1218d47 to your computer and use it in GitHub Desktop.
Save corruptmem/80c673a629dd3e0ce26a360ae1218d47 to your computer and use it in GitHub Desktop.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Repro
{
[Table("bar")]
public sealed class Bar : IThing
{
[Key, Column("id")]
public int Id { get; set; }
[Column("relation_id")]
public int RelationId { get; set; }
[ForeignKey(nameof(RelationId))]
public Relation Relation { get; set; }
}
[Table("foo")]
public sealed class Foo : IThing
{
[Key, Column("id")]
public int Id { get; set; }
[Column("relation_id")]
public int RelationId { get; set; }
[ForeignKey(nameof(RelationId))]
public Relation Relation { get; set; }
}
public interface IThing
{
int Id { get; }
Relation Relation { get; }
}
[Table("relation")]
public sealed class Relation
{
[Key, Column("id")]
public int Id { get; set; }
[Column("some_data")]
public string SomeData { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Bar>();
modelBuilder.Entity<Foo>();
}
}
public class Program
{
static void Main()
{
var services = new ServiceCollection();
var cs = "<redacted>";
services.AddDbContext<MyDbContext>(ctx => ctx.UseNpgsql(cs), ServiceLifetime.Transient);
services.AddLogging(l => l.AddConsole());
var provider = services.BuildServiceProvider();
using (var dbContext = provider.GetRequiredService<MyDbContext>())
{
var bars = dbContext.Set<Bar>().Include(x => x.Relation);
var foos = dbContext.Set<Foo>().Include(x => x.Relation);
var all = bars.Cast<IThing>().Concat(foos).OrderBy(x => x.Id);
Console.WriteLine(all.ToList().Count);
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<LangVersion>7.2</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.0-rc1-final" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.1.0-rc1-final" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.0-rc1" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment