Skip to content

Instantly share code, notes, and snippets.

@divega
Created July 26, 2018 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divega/d9c9757e0d5cce7f4d0772a2fdd51747 to your computer and use it in GitHub Desktop.
Save divega/d9c9757e0d5cce7f4d0772a2fdd51747 to your computer and use it in GitHub Desktop.
Mapping the same table to two objects
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace ConsoleApp33
{
class Program
{
static void Main(string[] args)
{
using (var context = new MyContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var people = context.People.ToList();
var peopleFlat = context.PeopleFlat.ToList();
}
}
}
public class MyContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbQuery<PersonFlat> PeopleFlat { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"server=(localdb)\MSSQLLocalDB;database=TestFlattening;integrated security=yes;connectretrycount=0");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>(); // sets up inhertiance
modelBuilder.Query<PersonFlat>().ToView("People");
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Student : Person
{
public string School { get; set; }
}
public class PersonFlat
{
public int Id { get; set; }
public string Name { get; set; }
public string School { get; set; }
public string Discriminator { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace ConsoleApp33
{
class Program
{
static void Main(string[] args)
{
using (var context = new MyContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var people = context.People.ToList();
var peopleFlat = context.PeopleFlat.ToList();
}
}
}
public class MyContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<PersonFlat> PeopleFlat { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"server=(localdb)\MSSQLLocalDB;database=TestFlattening;integrated security=yes;connectretrycount=0");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>(); // sets up inhertiance
modelBuilder.Entity<PersonFlat>().ToTable("People");
modelBuilder.Entity<PersonFlat>().HasOne<Person>().WithOne().HasForeignKey<PersonFlat>(pf=>pf.Id);
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Student : Person
{
public string School { get; set; }
}
public class PersonFlat
{
public int Id { get; set; }
public string Name { get; set; }
public string School { get; set; }
public string Discriminator { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment